您的位置:首页 > 其它

hdu 1213 并查集

2013-08-05 15:10 162 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1213

#include<iostream>
#include<cstdio>
using namespace std;
#define N 1000
int father
;
void ufset()
{
for(int i=0;i<N;i++)
father[i]=-1;
}
int find(int x)
{
int s;
for(s=x;father[s]>=0;s=father[s]);
while(s!=x)
{
int tmp=father[x];
father[x]=s;
x=tmp;
}
return x;
}
void Union(int R1,int R2)
{
int r1=find(R1),r2=find(R2);
int tmp=father[r1]+father[r2];
if(father[r1]>father[r2])
{
father[r1]=r2;
father[r2]=tmp;
}
else
{
father[r2]=r1;
father[r1]=tmp;
}
}
int main()
{
int n,sum,m,x,y;
// freopen("1.txt","r",stdin);
scanf("%d",&n);
while(n--)
{
int num=0;
scanf("%d%d",&sum,&m);
ufset();
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
if(find(x)!=find(y))
{
Union(x,y);
num++;
}
}
cout<<sum-num<<endl;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: