[ZOJ 2966] Build The Electric System (Minimum Spanning Tree Kruskal), zojkruskal
DescriptionIn last winter, there was a big snow storm in South China. the electric system was damaged seriously. lots of power lines were broken and lots of Ages lost contact with the main power grid. the government wants to reconstruct the electric system as soon as possible. so, as a professional programmer, you are asked to write a program to calculate the minimum cost to reconstruct the power lines to make sure there's at least one way between every two ages.
Input
Standard input will contain multiple test cases. The first line of the input is a single integerT(1 <=T<= 50) which is the number of test cases. And it will be followedTConsecutive test cases.
In each test case, the first line contains two positive integersNAndE(2 <=N<= 500,N<=E<=N*(N-1)/2), representing the number of the ages and the number of the original power lines between ages. There followELines, and each of them contains three integers,A,B,K(0 <=A,B<N, 0 <=K<1000 ).AAndBRespectively means the index of the starting village and ending village of the power line. IfKIs 0, it means this line still works fine after the snow storm. IfKIs a positive integer, it means this line will costKTo reconstruct. There will be at most one line between any two ages, and there will not be any line from one village to itself.
Output
For each test case in the input, there's only one line that contains the minimum cost to recover the electric system to make sure that there's at least one way between every two ages.
Sample Input
13 30 1 50 2 01 2 9
Sample Output
5
Question
Returns an undirected Edge band weight map and outputs the Minimum Spanning Tree.
# Include <iostream> # include <algorithm> using namespace std; int p [10005], n, e; struct edge {int x, y, w;} a [10005]; int cmp (edge a, edge B) {return. w <B. w;} int find (int r) {if (p [r]! = R) p [r] = find (p [r]); return p [r];} int k () {sort (a, a + e, cmp ); // be sure to sort by edge !!! Int ans = 0, I; for (I = 0; I <e; I ++) {int fx = find (a [I]. x), fy = find (a [I]. y); if (fx! = Fy) {p [fx] = fy; ans + = a [I]. w ;}} return ans;} int main () {int t, I; cin >>> t; while (t --) {cin >>> e; for (I = 0; I <= n; I ++) p [I] = I; for (I = 0; I <e; I ++) scanf ("% d", & a [I]. x, & a [I]. y, & a [I]. w); printf ("% d \ n", k ();} return 0 ;}