并查集

生日聚会难题

题目描述
生日聚会,认识的人可以做一张桌子。
If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

输入
输入第一行一个整数W,表示共测试W组数据。
第二行两个整数M,N分别表示共有几个人,和几个关系接下来N行表示N个关系。

输出
输出W组结果。

样例输入
2
5 3
1 2
2 3
4 5
5 1
2 5

样例输出
2
4

#include <iostream>
#include <algorithm>
using namespace std;
int s[1009] = {0};
void init(int n) {
    for (int i = 1; i <= n; i++) {
        s[i] = i;
    }
}
int find(int x) {
    int r = x;
    while (s[r] != r) {
        r = s[r];
    }
    return r;
}
void merge(int a, int b) {
    int x1 = find(a);
    int x2 = find(b);
    if (x1 != x2) {
        s[x2] = x1;
    }
}
int main() {
    int T, n, m, a, b;
    cin >> T;
    while (T--) {
        cin >> n >> m;
        init(n);
        for (int i = 0; i < m; i++) {
            cin >> a >> b;
            merge(a, b);
        }
        int cnt = 0;
        for (int i = 1; i <= n; i++) {
            if (i == s[i]) {
                cnt++;
            }
        }
        cout << cnt << endl;
    }
    return 0;
}

新郎的烦恼

题目描述
一个新郎要在饭店举行婚礼,为了避免尴尬,一个桌上至少有一对人相互认识,而且桌与桌之间没有一对人相互认识。新郎想知道至少需要安排多少桌酒席。一个前提是桌子足够大。

输入
第一行为来的总人数N(<1000)(序号从1到1000)。
第二行输入一个整数M。表示多少对人相互认识。
接下来的M行每行两个整数表示两个相互认识人的序号,中间用空格分开。

输出
输出一个整数表示需要多少桌酒席。

样例输入
10
5
1 2
1 3
3 4
4 5
7 8

样例输出
5

#include <iostream>
#include <algorithm>
using namespace std;
int s[1009] = {0};
void init(int n) {
    for (int i = 1; i <= n; i++) {
        s[i] = i;
    }
}
int find(int x) {
    int r = x;
    while (s[r] != r) {
        r = s[r];
    }
    return r;
}
void merge(int a, int b) {
    int x1 = find(a);
    int x2 = find(b);
    if (x1 != x2) {
        s[x2] = x1;
    }
}
int main() {
    int n, m, a, b;
    while (cin >> n >> m) {
        init(n);
        for (int i = 0; i < m; i++) {
            cin >> a >> b;
            merge(a, b);
        }
        int cnt = 0;
        for (int i = 1; i <= n; i++) {
            if (i == s[i]) {
                cnt++;
            }
        }
        cout << cnt << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值