Firm
Time limit2sMemory limit512 MB
Process hires and queries on a growing rooted tree, counting employees at exact depth offset k below a given node at query time.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Linked list, Binary search
- Solved
- No attempts yet
Problem
In a fast-growing firm, new employees are hired all the time. Every new employee is given exactly one direct superior. That superior's own superiors (direct and indirect) automatically become indirect superiors of as well.
We call the direct superior of a superior of degree . The superior of a degree- superior is a superior of degree , and in general the superior of a degree- superior is a superior of degree . So each employee is a subordinate of their direct superior and of every higher-degree superior above them. Together this forms a single hierarchy of all employees, with the company's founder at the very top.
The company keeps a full history of everyone who has joined since it was founded. From time to time an employee wants to know, for a given degree , how many current employees have them as a superior of exactly degree . Write a program that answers these questions.
Input
The first line contains an integer (), the number of events. The next lines each describe one event, in chronological order.
A hiring event is the character Z followed by two integers and (, and is distinct across all hires): is the number of the new employee and is the number of the direct superior. is always the number of an employee who is already working at the company. The founder has number .
A question event is the character P followed by two integers and (, ): employee asks how many current employees have as a superior of exactly degree .
Before the first event, the founder is the only person at the firm.
Output
For each question event, print a single line with one integer: the number of current employees for whom is a superior of exactly degree .
Hint
