Under construction

Still being built. Things may change

Random Road

Time limit3sMemory limit1024 MB

Summary
Given a tree with park beauties and randomly oriented one-way snake edges, find the expected beauty of a safe random walk from each starting park, modulo 1e9+7.
Level

Hard8 of 10

Topics
Dynamic programming, Tree, Probability, Math
Solved
No attempts yet

Problem

Vito lives in a city with nn parks labeled from 11 to nn. The parks are connected by n−1n - 1 roads, and there is a path between any two parks. Park ii has beauty viv_i.

Last night Vito decided to wander around the city. After he visits a park, he picks one of the roads leaving it with equal probability and moves to the park at the other end. Before he left, he looked out of his window and saw that each road has either a blue snake or a red snake. A blue snake attacks everyone who travels from the park with the lower label to the park with the higher label. A red snake attacks everyone who travels from the park with the higher label to the park with the lower label.

Vito does not want to be attacked, so when he picks a road at random, he only considers roads he can pass safely. He keeps walking as long as at least one safe road is available.

If each road is equally likely to have a blue snake or a red snake, what is the expected beauty of his journey starting at park ii? The beauty of a path is the sum of the beauties of the parks visited along it. The expected beauty is the sum, over all possible paths, of the path's beauty times the probability that Vito takes that path.

Input

The first line contains nn (2≤n≤1062 \le n \le 10^6). The second line contains n−1n - 1 integers pip_i (1≤pi<i1 \le p_i < i), meaning there is a road between park i+1i + 1 and park pip_i. The third line contains nn integers viv_i (0≤vi≤1060 \le v_i \le 10^6).

Output

If the expected beauty of Vito's journey starting at park ii is ab\frac{a}{b} for integers aa and bb, print ab−1 mod (109+7)a b^{-1} \bmod (10^9 + 7) on the ii-th line, where b−1b^{-1} is the modular inverse of bb modulo 109+710^9 + 7.

Hint

In the first example, the expected beauty starting from park 1 is 52\frac{5}{2}, which is 5⋅2−1 mod (109+7)=5000000065 \cdot 2^{-1} \bmod (10^9 + 7) = 500000006. Starting from park 2, it is 2.

In the second example, the probability that both snakes are red is 14\frac{1}{4}. In that case, if Vito starts at park 1, he picks which road to take at random.

Examples3

  1. Example 1

    Input
    2
    1
    2 1
    
    Expected output
    500000006
    2
    
  2. Example 2

    Input
    3
    1 1
    8 8 8
    
    Expected output
    14
    14
    14
    
  3. Example 3

    Input
    11
    1 1 1 2 3 4 1 2 6 2
    1 1000 5 3 18 200 8 9 0 2 2
    
    Expected output
    968750272
    610352580
    450521029
    536458466
    199219275
    662760680
    190972315
    90277951
    824219264
    941840425
    532552597