算法笔记p322

代码:

#include <iostream>
#include <cstdio>
#include <set>
#define maxn 105
using namespace std;

int father[maxn];

int findfather1(int x){
    while(x != father[x]){
        x = father[x];
    }
    
    return x;
}

int findfather2(int x){
    if(x == father[x]) return x;
    else
        return findfather2(father[x]);
}

int findfather3(int x){
    int a = x;
    while(x != father[x]){
        x = father[x];
    }
    
    while(a != father[a]){
        int z = a;
        a = father[a];
        father[z] = x;
    }
    
    return x;
}

int findfather4(int x){
    if(x == father[x]) return x;
    else{
        int v = findfather4(father[x]);
        father[x] = v;
        return v;
    }
}

void Union(int a,int b){
    int fa = father[a];
    int fb = father[b];
    if(fa != fb)
        father[fa] = fb;
}


int main(void){
    freopen("in.txt","r",stdin);
    
    int n,m;
    set<int> vi;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        father[i] = i;
    
    while(m--){
        int a,b;
        scanf("%d%d",&a,&b);
        Union(a,b);
    }
        
    for(int i=1;i<=n;i++)
        vi.insert(findfather4(i));
    printf("%d\n",vi.size());
    
    fclose(stdin);
    return 0;
}

 

posted @ 2019-03-03 16:36  pha创噬  阅读(153)  评论(0编辑  收藏  举报