hdu 1213 How Many Tables(并查集练习)

题目链接:hdu1213

赤裸裸的并查集。。。。。水题一个。。。。

 

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
#define MAXN 10
using namespace std;
int father[1005];
void build(int n)
{
    for(int i = 0 ; i <= n ; i ++)
    father[i] = i;
}
int find(int x)
{
    if(x != father[x])
    {
        father[x] = find(father[x]);
    }
    return father[x];
}
void Union(int x,int y)
{
    x = find(x);
    y = find(y);
    if(x == y) return;
    father[y] = x;
}
int main()
{
    int T,n,m,i,x,y;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        build(n);
        while(m--)
        {
            scanf("%d%d",&x,&y);
            Union(x,y);
        }
        int ans = 0;
        for(i = 1 ; i <= n ; i ++)
        if(father[i] == i) ans ++;
        printf("%d\n",ans);
    }
    return 0;
}


 

 

你可能感兴趣的:(table)