#P9701. [GDCPC 2023] Classic Problem

[GDCPC 2023] Classic Problem

题目描述

Given an undirected complete graph with nn vertices and mm triples P1,P2,,PmP_1, P_2, \cdots, P_m where Pi=(ui,vi,wi)P_i = (u_i, v_i, w_i), it's guaranteed that 1ui<vin1 \leq u_i < v_i \leq n, and for any two triples PiP_i and PjP_j with different indices we have (ui,vi)(uj,vj)(u_i, v_i) \ne (u_j, v_j).

For any two vertices xx and yy in the graph (1x<yn1 \leq x < y \leq n), define the weight of the edge connecting them as follows:

  • If there exists a triple PiP_i satisfying ui=xu_i = x and vi=yv_i = y, the weight of edge will be wiw_i.
  • Otherwise, the weight of edge will be xy|x - y|.

Calculate the total weight of edges in the minimum spanning tree of the graph.

输入格式

There are multiple test cases. The first line of the input contains an integer TT (1T1051 \le T \le 10^5) indicating the number of test cases. For each test case:

The first line contains two integers nn and mm (1n1091 \leq n \leq 10^9, 0m1050 \leq m \leq 10^5) indicating the number of vertices in the graph and the number of triples.

For the following mm lines, the ii-th line contains three integers uiu_i, viv_i and wiw_i (1ui<vin1 \leq u_i < v_i \leq n, 0wi1090 \leq w_i \leq 10^9) indicating the ii-th triple. It's guaranteed that for all 1i<jm1 \leq i < j \leq m we have (ui,vi)(uj,vj)(u_i, v_i) \ne (u_j, v_j).

It's guaranteed that the sum of mm of all test cases will not exceed 5×1055 \times 10^5.

输出格式

For each test case output one line containing one integer indicating the total weight of edges in the minimum spanning tree of the graph.

3
5 3
1 2 5
2 3 4
1 5 0
5 0
5 4
1 2 1000000000
1 3 1000000000
1 4 1000000000
1 5 1000000000
4
4
1000000003

提示

The first sample test case is illustrated as follows. The minimum spanning tree is marked by red segments.

The second sample test case is illustrated as follows. The minimum spanning tree is marked by red segments.

The third sample test case is illustrated as follows. The minimum spanning tree is marked by red segments.