Codeforces Round #434 (Div. 1) -E Arkady and a Nobody-men
Codeforces傳送門
洛谷傳送門
題目描述
Arkady words in a large company. There are nn employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees.
Each employee has an integer rank. The CEO has rank equal to , each other employee has rank equal to the rank of his immediate manager plus .
Arkady has a good post in the company, however, he feels that he is nobody in the company’s structure, and there are a lot of people who can replace him. He introduced the value of replaceability. Consider an employee and an employee , the latter being manager of aa (not necessarily immediate). Then the replaceability of with respect to is the number of subordinates (not necessarily immediate) of the manager , whose rank is not greater than the rank of . Apart from replaceability, Arkady introduced the value of negligibility. The negligibility of employee aa equals the sum of his replaceabilities with respect to all his managers, i.e. , where the sum is taken over all his managers .
Arkady is interested not only in negligibility of himself, but also in negligibility of all employees in the company. Find the negligibility of each employee for Arkady.
輸入輸出格式
輸入格式:
The first line contains single integer ( ) — the number of employees in the company.
The second line contains integers ( ), where if the -th employee is the CEO, otherwise equals the id of the immediate manager of the employee with id . The employees are numbered from to . It is guaranteed that there is exactly one among these values, and also that the CEO is a manager (not necessarily immediate) for all the other employees.
輸出格式:
Print integers — the negligibilities of all employees in the order of their ids: .
輸入輸出樣例
輸入樣例#1:
4
0 1 2 1
輸出樣例#1:
0 2 4 2
輸入樣例#2:
5
2 3 4 5 0
輸出樣例#2:
10 6 3 1 0
輸入樣例#3:
5
0 1 1 1 3
輸出樣例#3:
0 3 3 3 5
說明
Consider the first example:
- The CEO has no managers, thus .
- (employees and suit the conditions, employee has too large rank). Thus .
- Similarly,$ z_{4}=r(4,1)=2$ .
- (employee is a subordinate of and has suitable rank). (employees , , suit the conditions). Thus .
題目大意
給你一棵有根樹, 設 為 的祖先節點, 表示在 子樹中不超過 深度的點的個數(不包括 自己), 求對於所有點的 。
解題分析
很容易發現每個點 對於其他點 ( )的貢獻就是 , 所以將所有點按深度從小到大排序, 每次處理同一深度的點, 在其到根節點的路徑上區間 , 然後查詢其到根節點的路徑上的權值和即可, 總複雜度 , 卡卡常就過了。
這裡有一種 的做法。我們可以發現 ,那麼實際上我們只需要考慮同深度的點之間的貢獻。
將同深度的點按 序排序, 那麼可以發現對於一個排在第 位的點, 其前面的點從 開始, 它們的