In 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 villages 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 villages.
Input
Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 50) which is the number of test cases. And it will be followed by T consecutive test cases.
In each test case, the first line contains two positive integers N and E (2 <= N <= 500, N <= E <= N * (N - 1) / 2), representing the number of the villages and the number of the original power lines between villages. There follow E lines, and each of them contains three integers, A, B, K (0 <= A, B < N, 0 <= K < 1000). A and B respectively means the index of the starting village and ending village of the power line. If K is 0, it means this line still works fine after the snow storm. If K is a positive integer, it means this line will cost K to reconstruct. There will be at most one line between any two villages, 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 villages.
Sample Input
1 3 3 0 1 5 0 2 0 1 2 9
Sample Output
5
题意:有n个城市,有m条线路,每条线路a,b,c表示a到b的线路需要花费c的费用维修,要求能将所有城市联通的最小维修花费
思路:一开始按照花费从小到大将路线排序,然后再来一次并查集整合所有线路,知道全部联通
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; struct node { int s,t,c; } ss[40005]; int father[605]; int cmp(node x,node y) { return x.c<y.c; } int find(int x) { return father[x]=(father[x]==x?x:find(father[x])); } int main() { int t,n,m,i,ans; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i = 0; i<m; i++) scanf("%d%d%d",&ss[i].s,&ss[i].t,&ss[i].c); for(i = 0; i<n; i++) father[i] = i; sort(ss,ss+m,cmp); ans = 0; for(i = 0; i<m; i++) { int fx = find(ss[i].s); int fy = find(ss[i].t); if(fx!=fy) { ans+=ss[i].c; father[fx] = fy; } } printf("%d\n",ans); } return 0; }