HDU-1213-How Many Tables

链接:https://vjudge.net/problem/HDU-1213

题意:

给n个人m个连通,求有几组

思路:

并查集模板

代码:

#include <iostream>
#include <memory.h>
#include <string>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <map>
#include <queue>
#include <math.h>
using namespace std;
const int MAXN = 1000+10;
int Father[MAXN];

int Get_F(int x)
{
    return Father[x] = (Father[x] == x ? x : Get_F(Father[x]));
}

int main()
{
    int t;
    scanf("%d",&t);
    int n,m;
    int l,r;
    while (t--)
    {
        scanf("%d%d",&n,&m);
        for (int i = 1;i<=n;i++)
            Father[i] = i;
        for (int i = 1;i<=m;i++)
        {
            scanf("%d%d",&l,&r);
            int tl = Get_F(l);
            int tr = Get_F(r);
            if (tl != tr)
                Father[tr] = tl;
        }
        int sum = 0;
        for (int i = 1;i<=n;i++)
            if (Father[i] == i)
                sum++;
        printf("%d\n",sum);
    }

    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/YDDDD/p/10298241.html
今日推荐