Under construction

Still being built. Things may change

Clear Cold Water

Interview

Time limit1sMemory limit128 MB

Summary
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 NN pipes (3≤N≤999993 \le N \le 99999, with NN odd), numbered 1…N1 \dots N. 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 NN 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 11 is attached to the barn, and the distance from its endpoint to the barn is 11.

The map lists CC (1≤C≤N1 \le C \le N) branch points. Each branch point is given as three integers: the endpoint EiE_i (1≤Ei≤N1 \le E_i \le N) of a pipe, and the two pipes B1iB1_i and B2iB2_i (2≤B1i≤N2 \le B1_i \le N, 2≤B2i≤N2 \le B2_i \le N) that leave that endpoint. When a pipe branches, its distance carries on: the endpoints of B1iB1_i and B2iB2_i are one unit farther from the barn than the endpoint of EiE_i.

Using the map, report the distance from the barn to the endpoint of every pipe.

Input

  • Line 1: two space-separated integers, NN and CC.
  • Lines 2 to C+1C+1: line i+1i+1 describes one branch point with three space-separated integers EiE_i, B1iB1_i, and B2iB2_i. The endpoint of pipe EiE_i is a branch point from which pipes B1iB1_i and B2iB2_i leave.

Output

  • Lines 1 to NN: line ii contains a single integer, the distance from the barn to the endpoint of pipe ii.

Hint

The first example describes this pipe map:

+------+
| Barn |
+------+
   | 1
   *
2 / \ 3
     *
  4 / \ 5

Pipe 11 is always distance 11 from the barn. Pipes 22 and 33 branch from the endpoint of pipe 11, so they are distance 22. Pipes 44 and 55 branch from the endpoint of pipe 33, so they are distance 33.

Examples3

  1. Example 1

    Input
    5 2
    3 5 4
    1 2 3
    
    Expected output
    1
    2
    2
    3
    3
    
  2. Example 2

    Input
    3 1
    1 2 3
    
    Expected output
    1
    2
    2
    
  3. Example 3

    Input
    7 3
    1 2 3
    2 4 5
    4 6 7
    
    Expected output
    1
    2
    2
    3
    3
    4
    4