Lowest Common Ancestor
Time limit2sMemory limit512 MB
For a rooted tree with node weights, compute for each node i the sum of weights of LCA(i, j) over all j < i, where nodes are indexed by label order.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Prefix sum, Implementation
- Solved
- No attempts yet
Problem
Bobo has a rooted tree with nodes labeled . Node is the root, and the -th node has weight .
He wants to find , where
Input
The input contains zero or more test cases and ends at end-of-file. Each test case is given as follows.
The first line contains an integer ().
The second line contains integers ().
The third line contains integers , where denotes an edge from node to node (). The edges form a tree.
The sum of over all test cases does not exceed .
Output
For each test case, print integers .