HDU 1213 How Many Tables

来源:互联网 发布:安卓魔音通话变声软件 编辑:程序博客网 时间:2024/06/04 00:47

这是我刚刷的第一道并查集的题,纪念一下!!!!!!!!!

#include<iostream>

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
using namespace std;


int father[1232];
int findx(int x) {
    int  r=x;
    while(father[r]!=r) {
        r=father[r];
    }
    return r;
}


void merge(int x,int y) {
    int fx=findx(x);
    int fy=findx(y);
    if(fx!=fy) {
        father[fx]=fy;
    }
}
int n,m;


void init() {
    for(int i=1; i<=n; i++) {
        father[i]=i;
    }
}
int main() {
    int T;
    while(~scanf("%d",&T)) {
        while(T--) {
            scanf("%d%d",&n,&m);
            init();
            int x;
            int y;
            while(m--) {
                scanf("%d%d",&x,&y);
                merge(x,y);
            }
            int ans=0;
            for(int i=1; i<=n; i++) {
                if(father[i]==i) {
                    ans++;
                }
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}
0 0
原创粉丝点击