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.