Under construction

Still being built. Things may change

Wind of Change 2020

Time limit12sMemory limit1024 MB

Summary
Given two weighted trees on N vertices (edge weights may be negative), output one integer: the answer defined by the maximum distance over pairs of vertices in T1.
Level

Medium6 of 10

Topics
Tree, DFS, Dynamic programming
Solved
No attempts yet

Problem

There is a tree T1T_1 with NN vertices. Each vertex of T1T_1 is numbered from 1 to NN, and each edge has an integer weight (which may be negative). The maximum distance between two vertices of T1T_1 is called the diameter of the tree. The two vertices may be the same vertex.

Gu Jae-hyeon, a student who met this problem in a lab session, came up with the following approach. Root the tree at vertex 1. Then the distance between two vertices x,yx, y is

depth1(x)+depth1(y)−depth1(LCA1(x,y))−depth1(LCA1(x,y))depth_1(x) + depth_1(y) - depth_1(LCA_1(x, y)) - depth_1(LCA_1(x, y))

Here depth1(x)depth_1(x) is the distance from the root to vertex xx in T1T_1, and LCA1(x,y)LCA_1(x, y) is the lowest common ancestor of xx and yy in T1T_1. Gu uses a Sparse Table to find an LCA in O(log⁡N)O(\log N). So by taking the maximum of this value over all 1≤x,y≤N1 \le x, y \le N, the problem can be solved in O(N2log⁡N)O(N^2 \log N).

Input

The first line contains the number of vertices NN of both trees (1≤N≤4000001 \le N \le 400000).

The next N−1N-1 lines each contain three integers ui,vi,wiu_i, v_i, w_i. This means that tree T1T_1 has an edge of weight wiw_i connecting vertices uiu_i and viv_i (1≤ui,vi≤N1 \le u_i, v_i \le N, ∣wi∣≤231−1|w_i| \le 2^{31} - 1).

The next N−1N-1 lines each contain three integers ui,vi,wiu_i, v_i, w_i. This means that tree T2T_2 has an edge of weight wiw_i connecting vertices uiu_i and viv_i (1≤ui,vi≤N1 \le u_i, v_i \le N, ∣wi∣≤231−1|w_i| \le 2^{31} - 1).

Output

Print one integer, the answer to the problem.

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
    110
    
  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
    3328