Slowing down
Time limit1sMemory limit128 MB
For each cow in order, count how many pastures already occupied by earlier cows lie on the tree path from node 1 to that cow's pasture.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Prefix sum, Implementation
- Solved
- No attempts yet
Problem
Farmer John has cows, conveniently numbered . Every day each cow walks from the barn to her own private pasture.
The pastures form a tree of nodes; the barn sits at pasture . Exactly two-way paths connect the pastures, and any two directly connected pastures share exactly one path, so there is a unique route between any pair of pastures. Path connects pastures and .
Cow owns the private pasture . Every pasture is owned by exactly one cow, so is a permutation of .
The barn's narrow door lets only one cow leave at a time, and each cow waits until the cow before her has reached her own pasture. First cow leaves and walks from pasture to and starts eating there. Then cow leaves and walks from pasture to , and so on.
While cow walks to , she may pass through pastures already occupied by a cow that arrived earlier. Each time she enters such an occupied pasture she slows down to avoid disturbing her friend. In other words, cow slows down once for every earlier cow (among cows ) whose pasture lies on the route from the barn (pasture ) to .
In the network below, the number in parentheses is the owner of each pasture:
1 (3)
/ \
(1) 4 3 (5)
/ \
(2) 2 5 (4)
Cow walks to pasture and meets no one. Cow walks to pasture , passing the occupied pasture on the way, so she slows down once. Cow owns pasture (the barn) and slows down zero times. Cow walks to pasture , passing the occupied pastures and , slowing down twice. Cow walks to pasture , passing the occupied pasture , slowing down once.
Farmer John wants to know how many times each cow slows down.
Input
- Line : a single integer .
- Lines : line contains two space-separated integers and , a path between pastures and .
- Lines : line contains a single integer , the pasture owned by cow .
Output
- Lines : line contains a single integer, the number of times cow slows down on her way to pasture .