Problem:
Height of a Tree

Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node.

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given.

si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

The output consists of n lines. Print the height of each node 0, 1, 2, ..., n-1 in order.

Constraints

1 ≤ n ≤ 10,000

0 ≤ wi ≤ 1,000

Sample Input 1

4
0 1 2
1 2 1
1 3 3

Sample Output 1

5
3
4
5

Solution in Python3 (judge verdict: Time Limit Exceeded)

from collections import defaultdict
import sys
sys.setrecursionlimit(200000)

def dfs(source, edge_index, connect):
    if connect[source][edge_index][2] >= 0:
        return connect[source][edge_index][2]
    this_edge = connect[source][edge_index]
    this_edge[2] = this_edge[1]
    dest = this_edge[0]
    for i, (next_dest, weight, all_weight) in enumerate(connect[dest]):
        if next_dest != source:
            if connect[dest][i][2] < 0:
                this_edge[2] = max(this_edge[2], dfs(dest, i, connect) + this_edge[1])
            else:
                this_edge[2] = max(this_edge[2], connect[dest][i][2] + this_edge[1])
    return this_edge[2]

v_num = int(input())
connect = defaultdict(list)
for _ in range(v_num - 1):
    v1, v2, weight = (int(n) for n in input().split(" "))
    connect[v1].append([v2, weight, -1])
    connect[v2].append([v1, weight, -1])
for v in range(v_num):
    for i, (next_dest, weight, all_weight) in enumerate(connect[v]):
        if connect[v][i][2] < 0:
            connect[v][i][2] = dfs(v, i, connect)
for v in range(v_num):
    answer = 0
    for i, (next_dest, weight, all_weight) in enumerate(connect[v]):
        answer = max(answer, all_weight)
    print(answer)