Let denote the number of ways to improve the quality of roads for the subtree rooted at vertex . Let represent a child of vertex .
If the road (v, to) remains in bad condition, then all roads in the subtree rooted at vertex must be improved.
If the road (v, to) is improved, then the number of ways to improve the roads for the subtree rooted at vertex is equal to .
Let to_1, to_2, ..., to_k be the children of . Then
If is a leaf (a vertex with no children), then let f(v) = 1.
Example
Consider the examples provided in the problem statement. For each vertex , we'll record the value of .
In the first example, there are ways to improve the quality of roads such that on the path from city 1 to any other city, there is no more than one bad road. Bad roads are represented by dashed lines, while improved roads are represented by solid lines.
Algorithm implementation
All calculations are performed modulo MOD = 10^9 + 7.
#define MOD 1000000007The dfs function computes the value of — the number of ways to improve the quality of roads for the subtree rooted at vertex . The parent of is vertex .
long long dfs(int v, int p = -1)
{
long long s = 1;If to_1, to_2, ..., to_k are the children of , then
for (int to : g[v])
if (to != p)
{
long long sub = dfs(to, v);
s = (s * (sub + 1)) % MOD;
}
return s;
}Read the input data. Construct a tree.
scanf("%d", &n);
g.resize(n + 1);
for (i = 2; i <= n; i++)
{
scanf("%d", &p);
g[i].push_back(p);
g[p].push_back(i);
}Compute and print the result.
res = dfs(1);
printf("%lld\n", res);