Under construction

Still being built. Things may change

Farthest node in a weighted tree

Interview

Time limit1sMemory limit256 MB

Summary
For every node of a weighted tree with up to 50000 nodes, print its distance to the farthest node.
Level

Medium6 of 10

Topics
Tree, DFS
Solved
No attempts yet

Problem

A weighted tree is a tree where every edge carries a number giving that edge's length. All lengths are positive.

For each node of the tree, find the largest distance from that node to any other node. The distance between two nodes is the sum of the edge lengths along the path that joins them.

Input

The first line contains the number of nodes NN. (2≤N≤500002 \le N \le 50000)

Each of the next N−1N-1 lines describes one edge with three positive integers. The first two are the labels of the nodes the edge joins (from 11 to NN), and the third is the length of the edge. The total length of all edges does not exceed 231−12^{31}-1. The input always describes a valid tree.

Output

Print exactly NN lines. The kk-th line contains the distance from node kk to the node farthest from it. (k=1,2,…,Nk = 1, 2, \dots, N)

Examples4

  1. Example 1

    Input
    6
    1 5 3
    2 6 3
    6 1 1
    1 3 5
    4 6 4
    
    Expected output
    5
    9
    10
    10
    8
    6
    
  2. Example 2

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

    Input
    5
    1 2 4
    2 3 1
    3 4 6
    4 5 2
    
    Expected output
    13
    9
    8
    11
    13
    
  4. Example 4

    Input
    7
    1 2 5
    1 3 9
    1 4 2
    1 5 9
    1 6 1
    1 7 4
    
    Expected output
    9
    14
    18
    11
    18
    10
    13