zoj 2966 Build The Electric System(并查集)

来源:互联网 发布:js格式化时间戳format 编辑:程序博客网 时间:2024/05/19 23:05

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2966

转载请注明出处:http://blog.csdn.net/u012860063



Build The Electric System

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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 byT 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, ABK (0 <= AB < N, 0 <= K < 1000). A and Brespectively 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

13 30 1 50 2 01 2 9

Sample Output

5


Author: ZHOU, Ran
Source: The 5th Zhejiang Provincial Collegiate Programming Contest

代码如下:

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;int fa[505],m,n,ans;struct edge{int x,y,va;}e[20000];bool cmp(edge a,edge b){return a.va<b.va;}int find(int x){if(x==fa[x]) return x;return fa[x]=find(fa[x]);}void kruskal(){int i;for(i=0;i<n;i++)fa[i]=i;sort(e,e+m,cmp);for(i=0;i<m;i++){int x=find(e[i].x);int y=find(e[i].y);if(x!=y){ans+=e[i].va;fa[y]=x;}}}int main(){int i,j,t;while(scanf("%d",&t)!=EOF){while(t--){scanf("%d %d",&n,&m);ans=0;for(i=0;i<m;i++)scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].va);kruskal();printf("%d\n",ans);}}return 0;}


1 0