并查集

来源:互联网 发布:手机解压密码破解软件 编辑:程序博客网 时间:2024/05/22 11:35

生日聚会难题

题目描述
生日聚会,认识的人可以做一张桌子。
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;}
0 0
原创粉丝点击