#P6199. [EER1] 河童重工

[EER1] 河童重工

Description

There are nn locations on Youkai Mountain. The two transportation networks of the Crow Tengu and the Kappa are each made up of some undirected roads connecting these locations, and each road has its own length. If we view these roads as weighted edges, then the two networks can be represented as two trees with nn nodes, T1T_1 and T2T_2 (a connected undirected weighted graph with n1n-1 edges).

Kappa Heavy Industries now wants to build some new undirected roads. The cost to build a new undirected road (i,j)(i,j) is distT1(i,j)+distT2(i,j)dist_{T_1}(i,j)+dist_{T_2}(i,j), that is, the sum of the distances from ii to jj in T1T_1 and T2T_2. Kappa Heavy Industries must ensure that any two nodes on Youkai Mountain can reach each other using only the newly built roads. However, since spending too much may trigger an incident, they want the total cost of this project to be as small as possible.

Nitori is the chief designer of this project. Please help her compute the minimum possible total cost of building the new roads.

Input Format

The first line contains a positive integer nn, representing the number of nodes.

The next n1n-1 lines describe T1T_1. The ii-th line contains three integers $x_i, y_i, v_i(1 \leq x_i, y_i \leq n, 1 \leq v_i \leq 5000)$, indicating that there is an edge in T1T_1 of length viv_i connecting nodes xix_i and yiy_i.

The next n1n-1 lines describe T2T_2. The jj-th line contains three integers $x_j, y_j, v_j(1 \leq x_j, y_j \leq n, 1 \leq v_j \leq 5000)$, indicating that there is an edge in T2T_2 of length vjv_j connecting nodes xjx_j and yjy_j.

Output Format

Output one integer in a single line, representing the minimum total cost.

5
1 2 1
1 3 1
2 4 1
2 5 1
2 3 1
2 4 1
3 5 1
3 1 1

10

4
1 2 1
1 3 1
1 4 1
1 2 1
2 3 1
3 4 1 

8

Hint

For 100%100\% of the testdata, 2n1052 \leq n \leq 10^5.

This problem has 55 subtasks, with the following limits:

Subtask 11 (1515 points): guarantee 2n10002 \leq n \leq 1000.

Subtask 22 (1515 points): guarantee that T1T_1 and T2T_2 are both chains.

Subtask 33 (55 points): guarantee that T1T_1 and T2T_2 are exactly the same except for edge weights (that is, if the two trees are viewed as unweighted trees, then they are the same).

Subtask 44 (55 points): guarantee that T2T_2 is a chain.

Subtask 55 (6060 points): no special constraints.

Translated by ChatGPT 5