#P4412. [SHOI2004] 最小生成树

[SHOI2004] 最小生成树

Description

Given a simple graph G=V,E,WG=\langle V, E, W \rangle, where VV is the set of vertices, EE is the set of edges (no multiple edges; i.e., there is at most one edge between any two vertices), and WW is an integer-valued weight function defined on EE. A spanning tree TT on GG is given. Modify WW with the minimum total cost so that TT becomes a minimum spanning tree on GG (a graph may have multiple minimum spanning trees; it suffices that the sum of edge weights of TT is minimum). For any edge eEe \in E, the modification rules are:

  • Increase the weight of ee: set W(e)=W(e)+Δ(e)W'(e) = W(e) + \Delta(e), and the cost to modify this edge is Δ(e)\Delta(e).
  • Decrease the weight of ee: set W(e)=W(e)Δ(e)W'(e) = W(e) - \Delta(e), and the cost to modify this edge is Δ(e)\Delta(e).
  • Do not change the weight of ee: set W(e)=W(e)W'(e) = W(e), with modification cost Δ(e)=0\Delta(e)=0.

Note: The modified weight function WW' also takes integer values.

The total modification cost is S=eEΔ(e)S = \sum\limits_{e \in E} \Delta(e).

Input Format

The first line contains N,MN, M, where NN is the number of vertices and MM is the number of edges. Vertices are numbered 1,2,3,,N1,N1, 2, 3, \dots, N-1, N.

The next MM lines each contain three integers Ui,Vi,WiU_i, V_i, W_i, indicating there is an edge between vertices UiU_i and ViV_i with weight WiW_i.

Each edge appears exactly once in the input. Then, the next N1N-1 lines each contain two integers Xi,YiX_i, Y_i, indicating that the edge between XiX_i and YiY_i is an edge of TT.

Output Format

Output the minimum SS.

6 9
1 2 2
1 3 2
2 3 3
3 4 3
1 5 1
2 6 3
4 5 4
4 6 7
5 6 6
1 3
2 3
3 4
4 5
4 6
8

Hint

Edge (4,6)(4,6) has its weight changed from 77 to 33, with cost 44;
edge (1,2)(1,2) has its weight changed from 22 to 33, with cost 11;
edge (1,5)(1,5) has its weight changed from 11 to 44, with cost 33.

Therefore, the total cost is 4+1+3=84+1+3=8.

Constraints: 1N501 \le N \le 50, 1M15001 \le M \le 1500, 1Wi10001 \le W_i \le 1000.

Translated by ChatGPT 5