| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
自己第一个并查集的题目,小庆贺一下贴一下自己的代码,仅供参考
#include<stdio.h>
long int sum;
long int num[50001],father[50001],i,j;
void makeset(int n)
{
for(i=0;i<n;i++)
father[i]=-1;
num[i]=1;
}
long int find(int x)
{
long int r=x,q;
while(father[r]!=-1)
r=father[r];
while(x!=r)
{
q=father[x];
father[x]=r;
x=q;
}
return r;
}
void unionset(int a,int b)
{
if(a==b)return;
if(num[a]>num[b])
father[b]=a;
else father[a]=b;
if(num[a]==num[b])
num[b]++;
sum--;
}
int main()
{
long int n,m,a,b;
long int count=1;
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)break;
sum=n;
makeset(n);
for(i=0;i<m;i++)
{
scanf("%d",&a);
scanf("%d",&b);
a=find(a);
b=find(b);
unionset(a,b);
}
printf("%s%d%s%d\n","Case ",count,": ",sum);
count++;
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator