Roads Improvement#10684

Roads Improvement (Editorial)

Let denote the number of ways to improve the quality of roads for the subtree rooted at vertex . Let represent a child of vertex .

Let to_1, to_2, ..., to_k be the children of . Then

f(v) = (f(to_1) + 1) \cdot (f(to_2) + 1) \cdot ... \cdot (f(to_k) + 1)

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 1000000007

The 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

f(v) = (f(to_1) + 1) \cdot (f(to_2) + 1) \cdot ... \cdot (f(to_k) + 1)
  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);