并查集算法程序

#include<iostream>
#define MAXN 100001
using namespace std;
 
int father[MAXN],n,m,q;
 
int getfather(int v){
    if (father[v]==v)
       return v;
    return father[v]=getfather(father[v]);
}
 
bool same(int x,int y){
     return (getfather(x)==getfather(y));
}
void judge(int x,int y){
    int fx,fy;
    fx=getfather(x);
    fy=getfather(y);
    if (fx==fy) return ;
    father[fx]=fy;
}
void init_work(){
     cin>>n;//n代表子树数
     cin>>m;//m代表关系数
     cin>>q;//q代表询问数
     int i ;
     for ( i=1; i<=n; i++)
         father[i]=i;
     for ( i=1; i<=m; i++){
         int a,b;cin>>a>>b;
         judge(a,b);
     }
     int a,b;
     for ( i=1;i<=q;i++){
         cin>>a>>b;
         cout<<(same(a,b)?"friend":"enime")<<endl;
     }
}
posted @ 2012-11-29 12:36  东嘉CEO  阅读(207)  评论(0编辑  收藏  举报