HDU 1879 继续畅通工程

基础 Kruskal

#include <iostream>
#include
<stdio.h>
using namespace std;
const int MAXN = 101;

struct E{
int x,y;
int weight;
};

E edge[MAXN
*MAXN/2];
int G[MAXN][MAXN];
int father[MAXN];

int cmp(const void *d1, const void *d2){
return (*(E*)d1).weight - (*(E*)d2).weight;
}

void makeSet(int n){
for(int i = 0; i <= n;i++)
father[i]
= i;
}

int find(int x){
if(x != father[x])
father[x]
= find(father[x]);
return father[x];
}

void merge(int x, int y){
x
= find(x);
y
= find(y);
if(x > y)
father[x]
= y;
else
father[y]
= x;
}
int main(){
int n;
int x,y,weight,statu,cost;
while(cin >> n , n){
makeSet(n);
cost
= 0;
for(int i = 1; i <= n*(n-1)/2; i++){
scanf(
"%d%d%d%d",&edge[i].x,&edge[i].y,&edge[i].weight,&statu);
if(statu == 1){
int xx = find(edge[i].x);
int yy = find(edge[i].y);
if(xx != yy)
merge(xx,yy);
}
}
qsort(edge
+1,n*(n-1)/2,sizeof(E),cmp); //edge + 1
for(int i = 1; i <= n*(n-1)/2 ;i++){
int xx = find(edge[i].x);
int yy = find(edge[i].y);
if(xx != yy){
merge(xx,yy);
cost
+= edge[i].weight;
}
}
cout
<< cost << endl;
}
return 0;
}

posted @ 2011-04-21 14:16  L..  阅读(317)  评论(0编辑  收藏  举报