HDU1213 How Many Tables - 并查集

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1213

/* HDU1213 How Many Tables http://acm.hdu.edu.cn/showproblem.php?pid=1213 */
#include <iostream> 
#include <stdio.h> 
#include <algorithm> 
#include <memory.h> 
#include <set>
#include <vector>
using namespace std;

#define N 1005

int t;
int n, m;

int fa[N];
int find(int x)
{
    if (x == fa[x])
        return x;
    return fa[x] = find(fa[x]);
}
void merge(int x, int y)
{
    fa[find(y)] = find(x);
}

set<int> sset;
vector<int> v;
int main()
{
    //freopen("in", "r", stdin);
    int i, j;
    scanf("%d", &t);
    for (j = 0; j < t;j++)
    {
        scanf("%d%d", &n, &m);
        for (i = 1; i <= n; i++)
        {
            fa[i] = i;
        }
        sset.clear();
        int a, b;
        for (i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            if (find(a) != find(b))
                merge(a, b);
        }
        for (i = 1; i <= n; i++)
        {
            sset.insert(find(i));
        }
        int len = sset.size();
        char s[1]; //处理中间的空格行
        if (j != t - 1)
            gets(s);
        v.push_back(len);
    }
    for (i = 0; i < t; i++)
    {
        printf("%d\n", v[i]);
    }
    return 0;
}

你可能感兴趣的:(HDU1213 How Many Tables - 并查集)