HDU1213 How Many Tables - 并查集

来源:互联网 发布:数控程序员考试 编辑:程序博客网 时间:2024/04/30 08:49

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

/*HDU1213 How Many Tableshttp://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 1005int 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;}
0 0
原创粉丝点击