还是畅通工程
http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1007&cid=12467&hide=0
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 5 Accepted Submission(s) : 4
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
当N为0时,输入结束,该用例不被处理。
Output
Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
Sample Output
3 5
Hint
Huge input, scanf is recommended.
Source
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int parent[105];
struct Edge{
int from,to,price;
}edge[5100];
bool compare(Edge a,Edge b){
return a.price<b.price;
}
void init(int n){
for(int i=1;i<=n;i++)
parent[i]=i;
}
int find(int x){
while(x!=parent[x])
x=parent[x];
return x;
}
void merge(int x,int y){
x=find(x);
y=find(y);
parent[x]=y;
}
int main(){
int sum ,n;
while(scanf("%d",&n)&&n){
int m=(n*(n-1))/2;
init(n);
sum=0;
for(int i=1;i<=m;i++)
scanf("%d%d%d", &edge[i].from ,&edge[i].to,&edge[i].price);
sort(edge+1,edge+m+1,compare);
for(int i=1;i<=m&&n>1;i++){
int x=find(edge[i].from),y=find(edge[i].to);
if(x!=y){
merge(x,y);
n--;
sum+=edge[i].price;
}
}
printf("%d\n",sum);
}
return 0;
}