A regional power company models its distribution network as a tree of n substations, numbered 0 through n-1, with substation 0 being the main plant. Each of the n-1 transformer links connects two substations u and v and reports a step ratio w meaning: one volt measured at substation u corresponds to exactly w volts measured at substation v. The links are listed in no particular order and do not necessarily point away from the plant, but taken together they connect every substation into a single tree with no cycles. Fixing the plant's own reading at exactly 1 volt, determine every substation's reading relative to the plant. Because these ratios can multiply into numbers far too large to store exactly, and because reaching some substations requires walking a link backwards (dividing instead of multiplying), report every reading modulo the prime 1,000,000,007 — where 'dividing' modulo this prime means multiplying by the modular inverse.
n, the number of substations.n-1 lines: three integers u v w — a transformer link between substations u and v with step ratio w, meaning one volt at u corresponds to w volts at v.n integers separated by single spaces: the reading of substations 0, 1, ..., n-1 relative to the plant, each taken modulo 1,000,000,007. (Substation 0's own reading is always 1.)n <= 100000w <= 10^9u, v <= n-1, and u != vn-1 links form a tree that connects all n substations (no cycles, no repeated links, no self-links).Example 1
Input
3 0 1 2 1 2 5
Expected
1 2 10
Explanation
Station 0's reading is fixed at 1. The link 0 1 2 is read forward (0 to 1), so station 1's reading is 1*2=2. The link 1 2 5 is also read forward (1 to 2), so station 2's reading is 2*5=10. Output: 1 2 10.
Example 2
Input
3 1 0 3 1 2 4
Expected
1 333333336 333333337
Explanation
The link 1 0 3 means one volt at station 1 corresponds to 3 volts at station 0; since station 0 is fixed at 1, this link must be walked backwards, so station 1's reading is 1 times the modular inverse of 3, which is 333333336 modulo 1,000,000,007. The link 1 2 4 is read forward from station 1, so station 2's reading is 333333336*4 mod 1,000,000,007 = 333333337. Output: 1 333333336 333333337.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →