#include<stdio.h>
#include<algorithm>
using namespace std;
struct Edge{
int x,y,w;
}edge[110*110];
int n;
int father[110];
bool cmp(Edge a,Edge b){
return a.w<b.w;
}
void init(){
for(int i=1;i<n+1;i++){
father[i]=i;
}
}
int findFather(int x){
int a=x;
while(father[x]!=x){
x=father[x];
}
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
int Union(int a,int b){
int fa=findFather(a);
int fb=findFather(b);
if(fa!=fb){
father[fa]=fb;
return 0;
}else return -1;
}
int Kruskal(int n,int m){
sort(edge,edge+m,cmp);
int count1=0;
int ans=0;
for(int i=0;i<m;i++){
//int temp=Union(edge[i].x,edge[i].y);
if(findFather(edge[i].x)!=findFather(edge[i].y)){
Union(edge[i].x,edge[i].y);
ans+=edge[i].w;
count1++;
if(count1==n-1)break;
}
}
if(count1==n-1)return ans;
else return -1;
}
int main(){
while(1){
scanf("%d",&n);
if(n==0)break;
init();
int a,b,c,d;
int num=0;
for(int i=0;i<n*(n-1)/2;i++){
scanf("%d%d%d%d",&a,&b,&c,&d);
edge[num].x=a;
edge[num].y=b;
if(d==1){//已建好
edge[num].w=0;
}else{
edge[num].w=c;
}
num++;
}
int res=Kruskal(n,n*(n-1)/2);
printf("%d\n",res);
}
}
杭电oj-1879
猜你喜欢
转载自blog.csdn.net/weixin_46265246/article/details/105290589
今日推荐
周排行