poj 1703 Finde them, Catch them! (并查集)

跟2492基本一样,不多说。

code:

#include<cstdio>
using  namespace std ;
int f[ 100005] ;
int r[ 100005] ;
int n, m ;
int find_Set( int x){
     int temp ;
     if(x==f[x]){
         return x ;
    }
    temp = f[x] ;
    f[x] = find_Set(temp) ;
    r[x] = (r[x]+r[temp]) %  2 ; // 保持r[x]相对于根节点的稳定
     return f[x] ;
}
void Union( int x,  int y,  int fx,  int fy){
    f[fy] = fx ;
    r[fy] = (r[x]+r[y]+ 1) %  2 ;
}
int main(){
     int t, i, j, x, y, fx, fy ;
     char c ;
    scanf( " %d ", &t) ;
     while(t--){
        scanf( " %d%d ", &n, &m) ;
         for(i= 0; i<=n; i++){
            f[i] = i ;
            r[i] =  0 ;
        }
        getchar() ;
         while(m--){
            scanf( " %c%d%d ", &c, &x, &y) ;
            getchar() ;
            fx = find_Set(x) ;
            fy = find_Set(y) ;
             if(c== ' D '){
                Union(x, y, fx, fy) ;
            }
             if(c== ' A '){
                 if(fx==fy){
                     if(r[x]==r[y])
                        printf( " In the same gang.\n ") ;
                     else
                        printf( " In different gangs.\n ") ;
                }
                 else
                    printf( " Not sure yet.\n ") ;
            }
        }
    }
     return  0 ;

 

你可能感兴趣的:(catch)