您的位置:首页 > 其它

HDU 1879 继续畅通工程(最小生成树 Kruskal算法)

2011-05-31 20:13 691 查看
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define  M 101
typedef struct egde{
int e,s,weight;
bool build;
}egde;
egde info[M*M/2];
int c[M],n,num;
bool cmp(const egde a,const egde b){
if(a.build!=b.build)
return a.build<b.build;
return a.weight<b.weight;
}
int Find(int x){
while(x!=c[x])
x=c[x];
return x;
}
bool Union(int x,int y){
int a=Find(x),b=Find(y);
if(a==b)
return false;
num++;
c[a]=b;
return true;
}
void init(){
int b;
num=0;
for(int i=1;i<=n*(n-1)/2;i++){
scanf("%d %d %d %d",&info[i].e,&info[i].s,&info[i].weight,&b);
info[i].build=b?false:true;
i<=n?c[i]=i:1;
}
sort(info+1,info+n*(n-1)/2+1,cmp);
}
int MST_Kruskal(){
int mincost=0;
for(int i=1;i<=n*(n-1)/2 && num<n-1 ;i++){
if(Union(info[i].s,info[i].e))
mincost+=info[i].weight*info[i].build;
}
return mincost;
}
int main(){
while(cin>>n && n){
init();
cout<<MST_Kruskal()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: