Running Away From the Barn
Time limit1sMemory limit128 MB
For every node in a weighted tree rooted at node 1, count the descendants within total distance L along the downward path, including the node itself.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Binary search, Prefix sum
- Solved
- No attempts yet
Problem
It is milking time on the farm, but all the cows have run away! To round them up you first need to work out how far each cow could possibly have gone.
The farm has pastures () numbered , connected by bidirectional paths. The barn is at pasture , and every pasture is reachable from the barn, so the pastures form a tree rooted at the barn.
Every cow starts the morning in its own pasture. A cow only runs away from the barn (it never moves back toward it), and it is too lazy to travel a total distance greater than . For every pasture, determine how many distinct pastures a cow starting there could end up in (including its starting pasture).
Because the distances can be large, store them in 64-bit integers.
Input
- Line : two integers and (, ).
- Lines : line contains two integers and . Here () is the next pasture on the shortest path from pasture toward the barn (that is, the parent of pasture ), and () is the length of the path joining pasture and pasture .
Output
- Lines : print one integer per line. The number on line is how many pastures can be reached from pasture by following paths that lead strictly farther away from the barn (pasture ), such that the total distance travelled does not exceed .
Hint
In the example, cows from pasture can hide in pastures , , and . Cows from pasture can hide in pastures and . Pastures and are the farthest from the barn, so a cow there can only stay put.