POJ 2524

並查集

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 50000 + 10;
int p[maxn];
bool vis[maxn];
int tofind(int x){
    if(x == p[x]) return p[x];
    return p[x] = tofind(p[x]);
}
void join(int x, int y){
    int px = tofind(x);
    int py = tofind(y);
    p[px] = py;
}
int main(){
    int n, m, a, b, c, ans, case_ = 1;
    while(scanf("%d%d", &n, &m) , n + m){
        memset(vis, 0, sizeof(vis));
        for(int i = 1; i <= n; i++) p[i] = i;
        for(int i = 0; i <m; i++){
            scanf("%d%d", &a, &b);
            join(a, b);
        }
        ans = 0;
        for(int i = 1; i <= n; i++){
            c = tofind(i);
            if(!vis[c]){
                ans++;
                vis[c] = true;
            }
        }
        printf("Case %d: %d\n",case_++ , ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章