Under construction

Still being built. Things may change

Lowest Common Ancestor

Time limit2sMemory limit512 MB

Summary
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 nn nodes labeled 1,2,…,n1, 2, \dots, n. Node 11 is the root, and the ii-th node has weight w_iw\_i.

He wants to find f(2),f(3),…,f(n)f(2), f(3), \dots, f(n), where

f(i)=∑_j=1i−1w_LCA(i,j).f(i) = \sum\_{j = 1}^{i - 1} w\_{\mathrm{LCA}(i, j)}\text{.}

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 nn (2≤n≤2⋅1052 \leq n \leq 2 \cdot 10^5).

The second line contains nn integers w_1,w_2,…,w_nw\_1, w\_2, \dots, w\_n (1≤w_i≤1041 \leq w\_i \leq 10^4).

The third line contains (n−1)(n - 1) integers p_2,p_3,…,p_np\_2, p\_3, \dots, p\_n, where p_ip\_i denotes an edge from node p_ip\_i to node ii (1≤p_i≤n1 \leq p\_i \leq n). The edges form a tree.

The sum of nn over all test cases does not exceed 2⋅1052 \cdot 10^5.

Output

For each test case, print (n−1)(n - 1) integers f(2),f(3),…,f(n)f(2), f(3), \dots, f(n).

Examples1

  1. Example 1

    Input
    3
    1 2 3
    1 1
    5
    1 2 3 4 5
    1 2 2 1
    
    Expected output
    1
    2
    1
    3
    5
    4