Description:
There are n villages numbered 1, 2, 3, and n that should be built to make them accessible to each other.
Input data
30 990 692990 0 179692 179 2
Three villages,
0 990 692990 0 179692 179 0
The distance from 1 to 1, 2, and 3 is 0, 990, 692, respectively.
11 2
It means there is a road connected, that is, the road between 1 and 2.
Solution:
KruskalAlgorithmTo build the Minimum Spanning Tree.
# Include <algorithm> # include <iostream> # include <vector> using namespace STD; Class Road // defines the data type of the road {public: int L, R; int dis ;}; vector <road> A; // store the input road int parent [200]; // check the structure of the set, parent [I] indicates the parent node of I int root (int A) // query the root node of A {If (parent [a] = A) {return ;} return parent [a] = root (parent [a]);} void Merge (int A, int B) // combine the collection of a and B {int Ra = root (a); int RB = root (B); parent [Ra] = RB ;} bool CMP (Road A, road B) // sorting function {return. dis <B. DIS ;} Int main () {int N; CIN> N; For (INT I = 0; I <n; I ++) {parent [I] = I; // check the initialization of the Set} For (INT I = 0; I <n; I ++) {road TMP; TMP. L = I; for (Int J = 0; j <n; j ++) {TMP. R = J; CIN> TMP. DIS;. push_back (TMP) ;}} int Q; CIN >> Q; while (Q --) {int L, R; CIN >>> l >> R; merge (L-1, r-1);} Sort (. begin (),. end (), CMP); // sort int size =. size (); int ans = 0; For (INT I = 0; I <size; I ++) {If (root (A [I]. l )! = Root (A [I]. r) // if not in the same set {merge (A [I]. l, a [I]. r); ans + = A [I]. dis ;}} cout <ans <Endl; return 0 ;}