Corporate life after a hostile takeover
Time limit0.5sMemory limit1024 MB
Given two rooted trees on the same n employees, count for each employee how many others are descendants in both trees.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Prefix sum, Sorting
- Solved
- No attempts yet
Problem
JanuszPol is a Polish company with a long tradition. Its finances recently turned bad, and a foreign competitor took it over. The new board decided to rebuild the company organization from scratch. Until now the structure was a plain tree.
- Exactly one executive director has no superior.
- Every other employee has exactly one direct superior, and there are no cyclic relations.
Employee is a subordinate of employee if sits below in the tree, that is, if following direct superiors upward from reaches .
After the takeover the company employs the same people and stays organized as a tree, but every employee receives a different position, so the shape of the tree may change completely. The executive director keeps the position. Right now nobody dares to give orders to anyone else, because a subordinate may become a superior at any moment.
You are given the tree before the takeover and the tree after it. For every employee , determine how many people were subordinates of before and remain subordinates of after.
Input
The first line contains an integer (), the number of employees. Employees are numbered from to , and employee is the executive director. The second line describes the structure before the takeover with numbers , where is the number of the superior of employee . The third line contains numbers , where is the superior of employee after the takeover. Both descriptions define a proper tree rooted at .
Output
Print one line with numbers separated by spaces. The -th of them is the number of people who are subordinates of employee in both trees at once.