当N为0时输入结束。
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
#define M 100005
int f[M];
int t,sum;
struct node
{
int x,y,z,k;
}p[M];
bool cmp(node a,node b)
{
return (a.z<b.z);
}
int findset(int x)
{
if(x!=f[x])
f[x]=findset(f[x]);
return f[x];
}
void unionset(int x,int y,int z,int k)
{
int fx=findset(x);
int fy=findset(y);
if(fx!=fy)
{
t++;
sum+=z;
f[fy]=fx;
}
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
for(int i=1;i<=n;i++)
f[i]=i;
for(int i=0;i<n*(n-1)/2;i++)
{
scanf("%d%d%d%d",&p[i].x,&p[i].y,&p[i].z,&p[i].k);
if(p[i].k==1) // 特别注意这个。处理得非常巧妙。
p[i].z=0;
}
sort(p,p+n*(n-1)/2,cmp);
sum=0;
t=1;
for(int i=0;i<n*(n-1)/2;i++)
{
unionset(p[i].x,p[i].y,p[i].z,p[i].k);
if(t==n)
{
printf("%d\n",sum);
break;
}
}
}
return 0;
}
原文:http://www.cnblogs.com/jzssuanfa/p/6874697.html