hdu 1213

***并查集模板题

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<algorithm>

using namespace std;
typedef long long LL;
#define N 1010
#define INF 0x3f3f3f3f

int father[N];

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

int main()
{
    int T, n, m, a, b, x, y, p, ans, k;
    scanf("%d", &T);

    while(T--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 0; i <= n; i++)
            father[i] = i;
        for(int i = 1; i <= m; i++)
        {
            scanf("%d%d", &a, &b);
            x = Find(a);
            y = Find(b);
            if(x != y)
                father[x] = y;
        }

        p = Find(1);
        ans = 1;

        for(int i = 1; i <= n; i++)
        {
            k = Find(i);
            if(k != p)
            {
                ans++;
                father[k] = p;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

posted on 2016-08-01 17:55  南风丶丶  阅读(129)  评论(0编辑  收藏  举报