Tree Path CountMedium

Tree Path Count

MediumPractice library · +20 XPtreesdfs

Given a tree represented by a parent array, for each node, count how many nodes are in the subtree rooted at that node (including the node itself). Print these counts in the order the nodes appear in the parent array (node 0 to N-1).

Input

The first line contains an integer N. The second line contains N integers p_0, p_1, ..., p_{N-1}, where p_i is the parent of node i. The root is node 0, and its parent is -1. Nodes are numbered 0 to N-1.

Output

Print N integers, where the i-th integer is the size of the subtree rooted at node i.

Constraints

1 <= N <= 200000. The input represents a valid tree with root 0.

Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests

Example 1

Input
5
-1 0 0 1 1
Output
5 3 1 1 1

Node 0 is root. Children of 0 are 1, 2. Children of 1 are 3, 4. Subtree sizes: node 3 (1), node 4 (1), node 1 (1+1+1=3), node 2 (1), node 0 (1+3+1=5).

Example 2

Input
7
-1 0 0 1 1 2 2
Output
7 3 3 1 1 1 1

Node 0 is root. Children of 0 are 1, 2. Children of 1 are 3, 4. Children of 2 are 5, 6. Subtree sizes: 3(1), 4(1), 1(3), 5(1), 6(1), 2(3), 0(1+3+3=7).

Hints