Random Road
Time limit3sMemory limit1024 MB
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 parks labeled from to . The parks are connected by roads, and there is a path between any two parks. Park has beauty .
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 ? 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 (). The second line contains integers (), meaning there is a road between park and park . The third line contains integers ().
Output
If the expected beauty of Vito's journey starting at park is for integers and , print on the -th line, where is the modular inverse of modulo .
Hint
In the first example, the expected beauty starting from park 1 is , which is . Starting from park 2, it is 2.
In the second example, the probability that both snakes are red is . In that case, if Vito starts at park 1, he picks which road to take at random.