并查集

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int N, M, set[1010];
int find ( int x ) {
    return x==set[x]?x:set[x]= find ( set[x] );   
}
void Union ( int x, int y ) {
     int a = find (x), b = find(y);
     if ( a != b ) {
          set[a] =  b;    
     }    
}
int main () {
     int a, b, x, y, sum;
    
     while ( scanf ( "%d%d", &N, &M ), N!=0 ) {
            for ( int i = 1; i <= N; i++ )
                set[i] = i;
            for ( int i = 1; i <= M; i++ ) {
                scanf ( "%d%d", &a ,&b);
                x = find (a), y = find(b);
                if ( x!=y)
                    Union ( a, b );
            }
            sum = -1;
            for ( int i = 1; i <= N; i++ ) {
                if ( set[i] == i )  sum++;  
            }
            printf ( "%d\n", sum );
     }
     return 0;  
}
posted @ 2011-08-11 17:17  bcy  阅读(133)  评论(0编辑  收藏  举报