Find the shortest path

4.1

9 votes
Algorithms, Graphs, Medium, Shortest Path Algorithm
Problem

Given a weighted tree with N vertices and N1 edges. Let D(i,j) be the distance of the unique simple path from i to j in this tree (i.e., the path from i to j that will not visit any node more than once).

We construct a new directed graph with N vertices, for each pair of vertices (i,j) if i<j we add an edge from i to j with weight D(i,j).

Find the shortest path from 1 to all other vertices in the newly constructed graph.

Input

The first line contains one integer - N(2N8104)

The (i+1)th(1iN1) line contains three integers - ui,vi,wi(1ui<viN,|wi|109), meaning there is an edge with cost wi between vertices ui and vi. These edges describe the original tree.

Output

Output N integers, the ith integer represents the shortest path from 1 to i.

 

Sample Input
5
1 2 -2
1 3 1
2 4 5
2 5 -6
Sample Output
0 -2 -3 1 -10
Time Limit: 10
Memory Limit: 256
Source Limit:
Explanation

12 with cost D(1,2)=2

123 with cost D(1,2)+D(2,3)=3

1234 with cost D(1,2)+D(2,3)+D(3,4)=1

1235 with cost D(1,2)+D(2,3)+D(3,5)=10

 

Editor Image

?