Clear Cold Water
InterviewTime limit1sMemory limit128 MB
Given a rooted binary tree described by branch points, print the distance from the barn to the endpoint of every pipe.
- Level
Medium4 of 10
- Topics
- Tree, BFS, Graph, Implementation
- Solved
- No attempts yet
Problem
The hot, humid summers of Wisconsin's dairy country make the cows thirsty, so Farmer John pumps clear cold water from the barn out into a network of pipes to keep the herd cool. There are pipes (, with odd), numbered . As the water flows through the pipes the summer heat warms it, so Bessie wants to know how far every point in the network is from the barn in order to find the coldest water.
The pipes form a binary tree rooted at the barn. Every branch point has exactly two pipes leaving it, every pipe is exactly one unit long, and all pipes connect into this single tree.
Each pipe has an endpoint that is either a branch point or an open spigot, and that endpoint is identified by the pipe's own number. Pipe is attached to the barn, and the distance from its endpoint to the barn is .
The map lists () branch points. Each branch point is given as three integers: the endpoint () of a pipe, and the two pipes and (, ) that leave that endpoint. When a pipe branches, its distance carries on: the endpoints of and are one unit farther from the barn than the endpoint of .
Using the map, report the distance from the barn to the endpoint of every pipe.
Input
- Line 1: two space-separated integers, and .
- Lines 2 to : line describes one branch point with three space-separated integers , , and . The endpoint of pipe is a branch point from which pipes and leave.
Output
- Lines 1 to : line contains a single integer, the distance from the barn to the endpoint of pipe .
Hint
The first example describes this pipe map:
+------+
| Barn |
+------+
| 1
*
2 / \ 3
*
4 / \ 5
Pipe is always distance from the barn. Pipes and branch from the endpoint of pipe , so they are distance . Pipes and branch from the endpoint of pipe , so they are distance .