HDU-1879-继续畅通工程(并查集)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1879

这题做的我好尴尬,虽然自己做出来了,感觉也不难,不过怎觉得,

对这个最小生成树的理解,好像总隔了一成迷雾,

题目不难,只要那个排序先优先,修建状态:1表示已建,的1,即已修建的,

再考虑按成本成小到大排序,即可

我的AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct node
{
int x,y,d,f;
}s[5000];

int father[111];
int sum;

bool cmp(const node &a,const node &b)
{
if(a.f!=b.f)
return a.f>b.f;
else
return a.d<b.d;
}

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

void Union(int x,int y,int d,int f)
{
x=Find(x);
y=Find(y);
if(x!=y)
{
father[x]=y;
if(f==0)
sum=sum+d;
}
}

int main(void)
{
int n,m,i,j,k,l;
while(scanf("%d",&n)==1&&n)
{
m=n*(n-1)/2;
for(i=0;i<m;i++)
scanf("%d%d%d%d",&s[i].x,&s[i].y,&s[i].d,&s[i].f);
sort(s,s+m,cmp);
for(i=1;i<=n;i++)
father[i]=i;
sum=0;
for(i=0;i<m;i++)
{
Union(s[i].x,s[i].y,s[i].d,s[i].f);
}
printf("%d\n",sum);
}
return 0;
}

posted @ 2014-08-27 10:05  立刻行动  阅读(132)  评论(0编辑  收藏  举报