| ||||||||||
| 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 <iostream>
const int MAX = 50001;
int p[MAX],rank[MAX];
int result;
int findSet(int x)
{
if(x!=p[x])
p[x] = findSet(p[x]);
return p[x];
}
void Union(int x, int y)
{
if(x == y)
return;
result--;
if(rank[x] > rank[y])
{
p[y] = x;
}
else
{
p[x] = y;
if(rank[x] == rank[y])
rank[y]++;
}
}
int main()
{
int i,j;
int s1,s2;
int x,y;
int n,m;
int t = 1;
while(true)
{
scanf("%d %d",&n,&m);
if(n==0&&m==0) break;
result = n;
for(i = 1; i <= n; i++)
{
p[i] = i;
rank[i] = 0;
}
for(i = 1; i <= m; i++)
{
scanf("%d %d",&x,&y);
s1 = findSet(x);
s2 = findSet(y);
Union(s1,s2);
}
printf("Case %d: ",t++);
printf("%d\n",result);
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator