# 并查集总结【模板】例题：①简单POJ - 1611The Suspects②一般HDU - 1272小希的迷宫

xiaoxiao2021-02-28  1

# 并查集

## 优化

1、按秩合并（按照树的高度合并） -> rank

【为了避免退化，对于每个集合维护一个rank值，每次将较小的合并到较大的，相同时则rank=rank+1】 按秩合并的基本思想是**使包含较少结点的树的根指向包含较多结点的树的根**，而这个树的大小可以抽象为树的高度，即高度小的树合并到高度大的树，这样资源利用更加合理。 为了实现一个按秩合并的不想交集合森林，要记录下秩的变化。对于每个结点x，有一个整数rank[x]，它是x的高度（从x到其某一个后代叶结点的最长路径上边的数目）的一个上界。（即树高）。当由 init 创建了一个单元集时，对应的树中结点的初始秩为0，每个 find 操作不改变任何秩。当对两棵树应用 merge 时，有两种情况，具体取决于根是否有相等的秩。当两个秩不相等时，我们使具有高秩的根成为具有较低秩的根的父结点，但秩本身保持不变。当两个秩相同时，任选一个根作为父结点，并增加其秩的值路径压缩。 尽管在路径压缩过程中，我们将数的高度改变了，但是我们不会改变rank秩的值，我们记录下的高度为虚拟高度。 //按秩合并 void init() { for(int i = 0; i <= n; i++) { fa[i] = i; rank[i] = 0; } } void merge(int x, int y) { int fx = find(x), fy = find(y); if(rank[fx] < rank[fy]) fa[fx] = fy; else { fa[fy] = fx; if(rank[fx] == rank[fy]) rank[fx]++; } }

2. 按大小合并（按照集合内元素数量合并） -> num

void init() { for(int i = 0; i < n; i++) { fa[i] = i; num[i] = 1; } } void merge(int x, int y) { int fx = find(x), fy = find(y); if(fx != fy) { fa[fx] = fy; num[fy] += num[fx]; } return; }

### 判断连通块的个数

for(int i = 0; i < n; i++) if(Find(i) == i) ans++;

# 【按大小合并】POJ - 1611 The Suspects

POJ - 1611 The Suspects

Description Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. To minimize transmission to others, the best strategy is to separate the suspects from others. In the Not-Spreading-Your-Sickness University (NSYSU), there are many student groups. Students in the same group intercommunicate with each other frequently, and a student may join several groups. To prevent the possible transmissions of SARS, the NSYSU collects the member lists of all student groups, and makes the following rule in their standard operation procedure (SOP). Once a member in a group is a suspect, all members in the group are suspects. However, they find that it is not easy to identify all the suspects when a student is recognized as a suspect. Your job is to write a program which finds all the suspects.

Input The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space. A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.

Output

For each case, output the number of suspects in one line.

Sample Input

100 4 2 1 2 5 10 13 11 12 14 2 0 1 2 99 2 200 2 1 5 5 1 2 3 4 5 1 0 0 0

Sample Output

4 1 1

#include <stdio.h> #include <iostream> #define maxn 30005 using namespace std; int fa[maxn], num[maxn], a[maxn], n, m; void init() { for(int i = 0; i < n; i++) { fa[i] = i; num[i] = 1; } } int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void merge(int x, int y) { int fx = find(x), fy = find(y); if(fx != fy) { fa[fx] = fy; num[fy] += num[fx]; } return; } int main() { while(scanf("%d%d", &n, &m) != EOF) { if(n == 0 && m == 0) break; init(); int t; while(m--) { scanf("%d", &t); for(int i = 0; i < t; i++) { scanf("%d", &a[i]); } for(int i = 0; i < t - 1; i++) { merge(a[i], a[i + 1]); } } int father = find(0); printf("%d\n", num[father]); } return 0; }

# HDU - 1272 小希的迷宫

HDU - 1272 小希的迷宫

Problem Description 上次Gardon的迷宫城堡小希玩了很久（见Problem B），现在她也想设计一个迷宫让Gardon来走。但是她设计迷宫的思路不一样，首先她认为所有的通道都应该是双向连通的，就是说如果有一个通道连通了房间A和B，那么既可以通过它从房间A走到房间B，也可以通过它从房间B走到房间A，为了提高难度，小希希望任意两个房间有且仅有一条路径可以相通（除非走了回头路）。小希现在把她的设计图给你，让你帮忙判断她的设计图是否符合她的设计思路。比如下面的例子，前两个是符合条件的，但是最后一个却有两种方法从5到达8。

Input 输入包含多组数据，每组数据是一个以0 0结尾的整数对列表，表示了一条通道连接的两个房间的编号。房间的编号至少为1，且不超过100000。每两组数据之间有一个空行。 整个文件以两个-1结尾。

Output 对于输入的每一组数据，输出仅包括一行。如果该迷宫符合小希的思路，那么输出"Yes"，否则输出"No"。

Sample Input

6 8 5 3 5 2 6 4 5 6 0 0

8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0

3 8 6 8 6 4 5 3 5 6 5 2 0 0

-1 -1

Sample Output

Yes Yes No

#include <stdio.h> #include <iostream> #include <map> #include <string.h> #define maxn 100010 using namespace std; int fa[maxn], vis[maxn], flag; void init() { for(int i = 1; i < maxn; i++) fa[i] = i; memset(vis, 0, sizeof(vis)); flag = 0; } int find(int x) { int z = x; while(fa[z] != z) z = fa[z]; int i = x, j; while(i != z) { j = fa[i]; fa[i] = z; i = j; } return z; } bool merge(int x, int y) { int fx = find(x), fy = find(y); if(fx != fy) { fa[fx] = fy; return true; } else return false; } int main() { int a, b; init(); while(scanf("%d%d", &a, &b) != EOF) { if(a == -1 && b == -1) break; if(a == 0 && b == 0) { if(flag == 1) printf("No\n"); else { int cnt = 0; for(int i = 1; i < maxn; i++) { if(vis[i] && find(i) == i) cnt++; } if(cnt > 1) printf("No\n"); else printf("Yes\n"); } init(); continue; } vis[a] = 1; vis[b] = 1; if(!merge(a, b)) flag = 1; } return 0; }