首页 > 代码库 > HDU-1233-还是畅通工程(并查集)

HDU-1233-还是畅通工程(并查集)

题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=1233
题目很简单(最小生成树)

#include<cstdio>#include<iostream>#include<algorithm>
using namespace std;struct node{ int x,y,d;}s[5000];int father[111];int sum;bool cmp(const node &a,const node &b){ 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){ x=Find(x); y=Find(y); if(x!=y) { father[x]=y; 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",&s[i].x,&s[i].y,&s[i].d); 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); } printf("%d\n",sum); } return 0;}

HDU-1233-还是畅通工程(并查集)