Who Answers to Whom

easy trees dfs graphs 1500 ms · 256 MB

Who Answers to Whom

A company has n employees, numbered from 1 to n. Exactly one of them is the CEO, who has no manager. Every other employee names exactly one direct manager, who is also an employee of the company. Following managers from any employee eventually reaches the CEO, and no employee is their own manager, direct or indirect.

For every employee, find how many employees answer to them — directly, or through a chain of managers below them. In other words, count everyone in the part of the organization that reports up to that employee, no matter how many levels down.

Input

The first line contains one integer n (1 ≤ n ≤ 2·10^5), the number of employees.

The second line contains n integers m_1, m_2, …, m_n (0 ≤ m_i ≤ n). If employee i is the CEO then m_i = 0; otherwise m_i is the id of employee i's direct manager, and m_i ≠ i. Exactly one m_i is 0. The manager relationships are guaranteed to be consistent: starting from any employee and repeatedly following direct managers reaches the CEO in a finite number of steps.

Output

Print n integers separated by spaces: the i-th of them is the number of employees who answer to employee i, directly or indirectly. The CEO's answer counts everybody else; an employee with no one below them answers 0.

Notes

In the first example, employee 2 is the CEO. Employee 1 manages employee 4 directly, so employee 1's count is 1. Employee 2 manages employees 1 and 3 directly, and employee 4 indirectly through employee 1, for a total of 3. Employees 3 and 4 have nobody below them, so their counts are 0.

In the second example, employee 3 is the CEO and everyone else reports directly to employee 3, so employee 3's count is 4 and everyone else's is 0.

The CEO is not necessarily employee 1, and a chain of managers can be up to n − 1 levels deep. Recomputing one employee's descendant count at a time by walking their whole subtree from scratch is too slow to finish in time for the largest inputs.

Example 1

Input

4
2 0 2 1

Output

1 3 0 0

Example 2

Input

5
3 3 0 3 3

Output

0 0 4 0 0

Hints · reveal one at a time if you're stuck

Hint 1

The management structure is a rooted tree, and each employee's answer is the number of people below them in it. Think about how a node's total below it can be built from its direct reports.

Hint 2

Find the CEO and visit everyone in top-down order, for example with a breadth-first search. Then go through that order in reverse, adding each employee's total into their manager's count, so every employee is finished before it is added. This avoids deep recursion on long chains.

report an issue Prefer your own editor? sooks prep 96 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.