Wind of Change

Time limit10sMemory limit1024 MB

Summary
Two weighted trees on the same vertex labels define a distance as the sum of both tree distances; for every vertex find the nearest other vertex under that combined metric.
Level

Hard9 of 10

Topics
Tree, Divide and conquer, DFS, Shortest path
Solved
No attempts yet

Problem

The original title of this problem is "Tree Product Metric Voronoi Diagram Query Without One Point".

You are given two weighted trees T1, T2T_1,\ T_2 of size NN, where each vertex is labeled with a number 1…N1 \ldots N. Let dist(T1, i, j)dist(T_1,\ i,\ j) be the total weight of the shortest path from node ii to jj in tree T1T_1, and define dist(T2, i, j)dist(T_2,\ i,\ j) the same way.

Consider a point set of size NN. Similar to the Manhattan metric (in fact, this is a generalization of it), we can define the distance between two points 1≤i, j≤N1 \le i,\ j \le N as the sum of two distances, dist(T1, i, j)+dist(T2, i, j)dist(T_1,\ i,\ j) + dist(T_2,\ i,\ j). For each 1≤i≤N1 \le i \le N, find the closest point to point ii. Formally, for each ii, you should find minj≠idist(T1, i, j)+dist(T2, i, j)min_{j \neq i}{dist(T_1,\ i,\ j) + dist(T_2,\ i,\ j)}.

Input

The first line contains a single integer NN, the number of vertices in both trees. (2≤N≤250 0002 \le N \le 250\,000)

The next N−1N-1 lines describe the first tree. Each line contains three integers Si, Ei, WiS_i,\ E_i,\ W_i, which means there is an edge connecting vertices SiS_i and EiE_i with weight WiW_i. (1≤Si, Ei≤N, 1≤Wi≤1091 \le S_i,\ E_i \le N,\ 1 \le W_i \le 10^9)

The next N−1N-1 lines describe the second tree in the same format.

Output

Print NN lines, each containing a single integer. The ii-th line holds the answer for point ii.

Examples2

  1. Example 1

    Input
    5
    1 2 10
    2 4 20
    3 4 30
    4 5 50
    1 2 15
    1 3 25
    1 4 35
    1 5 25
    
    Expected output
    25
    25
    85
    65
    105
    
  2. Example 2

    Input
    9
    5 7 6577
    4 5 8869
    5 9 9088
    2 1 124
    6 2 410
    2 8 8154
    4 8 4810
    3 4 4268
    3 9 763
    6 2 8959
    7 4 7984
    3 8 504
    8 6 9085
    5 2 4861
    1 9 8539
    1 7 7834
    
    Expected output
    18084
    9369
    9582
    23430
    26694
    9369
    23430
    9582
    22988