Build The Electric System
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 8 Accepted Submission(s) : 6
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
题意:几个村庄,经过天灾后,路部分断了,并给出了村庄与村庄之间的距离,距离为零则说明没断!
求使村庄连接修最短的路!。。,算是裸裸的模板!
代码:
#include<stdio.h> #include<algorithm> using namespace std; #define N 500 int country,road,set[N]; struct line { int bg; int ed; int dis; }num[N*N]; int cmp(line a,line b) { return a.dis<b.dis ; } int find(int p)//查找 { int t; int child=p; while(p!=set[p]) { p=set[p]; } while(p!=child) { t=set[child]; set[child]=p; child=p; } return p; } int merge(int x,int y)//合并 { int fx=find(x); int fy=find(y); if(fx!=fy) { set[fx]=fy; return 1; } return 0; } int main() { int n; scanf("%d",&n); while(n--) { int i,k; scanf("%d%d",&country,&road); for(i=0;i<=country;i++) { set[i]=i; } int a,b,c; for(i=0;i<road;i++) { scanf("%d%d%d",&num[i].bg ,&num[i].ed ,&num[i].dis ); } sort(num,num+road,cmp); int outcome=0; for(i=0;i<road;i++) { if(merge(num[i].bg ,num[i].ed ))//判断成环 outcome+=num[i].dis ; } printf("%d\n",outcome); } return 0; }