码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1213

时间:2016-08-01 19:31:54      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

***并查集模板题

#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;
}

 

hdu 1213

标签:

原文地址:http://www.cnblogs.com/9968jie/p/5726724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!