HDU 1213 How Many Tables(并查集)

题目链接:
HDU 1213 How Many Tables

题意:
有N位朋友,如果A朋友和B朋友认识,B朋友和C朋友认识,那么A、B、C都互相认识。互相认识的朋友坐一桌。
给出m对互相认识的朋友,问最少需要多少桌?

分析:
直接对每对互相认识的朋友合并,然后逐一将每位朋友的祖先标记下(find(i)),
然后统计有多少位朋友被标记了就是需要的最少桌子数量。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
#include <cmath>
using namespace std;

const int maxn = 1010;

int pre[maxn], vis[maxn];
int T, n, m, a, b;

/*
int find(int x)
{
    return pre[x] == x ? x : pre[x] = find(pre[x]);
}
*/

int find(int x)
{
    int r = x;
    while (pre[r] != r)
        r = pre[r];
    int i = x, j;
    while (pre[i] != r)
    {
        j = pre[i];
        pre[i] = r;
        i = j;
    }
    return r;
}

void mix(int x, int y)
{
    int fx = find(x);
    int fy = find(y);
    if (fx != fy)
    {
        if (fy < fx) swap(fx, fy);
        pre[fy] = fx;
    }
}

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
#endif
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++)
            pre[i] = i;
        for (int i = 1; i <= m; i++)
        {
            scanf("%d%d", &a, &b);
            mix(a, b);
        }
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= n; i++)
            vis[find(i)] = 1;
        int ans = 0;
        for (int i = 1; i <= n; i++)
            ans += vis[i];
        printf("%d\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值