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.
并查集三部曲:
- 初始化
- 合并
- 查询
#include <iostream>
using namespace std;
const int N = 40000;
int q[N];
int n, m;
void init() {
for (int i = 0; i <= n; i ++)
q[i] = i;
}
int find(int x) {
if (x != q[x]) {
return find(q[x]);
}
return x;
}
void merge(int x, int y) {
int a = find(x);
int b = find(y);
if (a != b) {
q[a] = b;
}
}
int main() {
while(cin >> n >> m) {
if (n == 0 && m == 0) {
break;
}
init(); // 初始化并查集
for (int j = 0; j < m; j ++) {
int k;
cin >> k;
int a, b;
cin >> a;
for (int i = 1; i < k; i ++) {
cin >> b;
merge(a, b);
}
}
int res = 1;
int t = find(0); // 0号的祖先
for (int i = 1; i <= n; i ++) { // 统计与0号共同祖先的数量
if (find(i) == t) {
res ++;
}
}
cout << res << endl;
}
return 0;
}
优化版本
#include <iostream>
using namespace std;
const int N = 40000;
int par[N];
int ranks[N]; // 记录树的高度
int n, m;
void init() {
for (int i = 0; i <= n; i ++) {
par[i] = i;
ranks[i] = 0;
}
}
int find(int x) {
if (x != par[x]) {
par[x] = find(par[x]); //路径压缩,优化
return par[x];
}
return x;
}
void merge(int x, int y) {
int a = find(x);
int b = find(y);
if (ranks[a] > ranks[b]) {
par[b] = a;
} else {
par[a] = b;
if (ranks[a] == ranks[b]) {
ranks[b] ++;
}
}
}
int main() {
while(cin >> n >> m) {
if (n == 0 && m == 0) {
break;
}
init(); // 初始化并查集
for (int j = 0; j < m; j ++) {
int k;
cin >> k;
int a, b;
cin >> a;
for (int i = 1; i < k; i ++) {
cin >> b;
merge(a, b);
}
}
int res = 1;
int t = find(0); // 0号的祖先
for (int i = 1; i <= n; i ++) { // 统计与0号共同祖先的数量
if (find(i) == t) {
res ++;
}
}
cout << res << endl;
}
return 0;
}