poj2524

简单并查集

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
using namespace std;

#define maxn 50004

int father[maxn];

int getanc( int a)
{
if (father[a] == a)
return a;
return father[a] = getanc(father[a]);
}

void merge( int a, int b)
{
if (father[a] == - 1 )
father[a]
= a;
if (father[b] == - 1 )
father[b]
= b;
father[getanc(a)]
= getanc(b);
}

int main()
{
// freopen("t.txt", "r", stdin);
int t = 0 ;
int n, m;
while (scanf( " %d%d " , & n, & m), n | m)
{
memset(father,
- 1 , sizeof (father));
t
++ ;
for ( int i = 0 ; i < m; i ++ )
{
int a, b;
scanf(
" %d%d " , & a, & b);
a
-- ;
b
-- ;
merge(a, b);
}
int ans = 0 ;
for ( int i = 0 ; i < n; i ++ )
if (father[i] == - 1 || father[i] == i)
ans
++ ;
printf(
" Case %d: %d\n " , t, ans);
}
return 0 ;
}

你可能感兴趣的:(poj)