您的位置:首页 > 其它

POJ 1611 The Suspects——并查集

2017-09-14 12:01 351 查看
建立集合看看那些人和0号人在一个集合中就可以

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 5 * 1e4;
int par[MAXN], ran[MAXN];
int N, M;
void Init() {
for (int i = 0; i < N; i++) par[i] = i, ran[i] = 0;
}
int Query(int x) {
return (x == par[x]) ? x : par[x] = Query(par[x]);
}
void Union(int x, int y) {
x = Query(x), y = Query(y);
if (x == y) return;
if (ran[x] < ran[y]) {
par[x] = y;
}
else {
par[y] = x;
if (ran[x] == ran[y]) ran[x]++;
}
}
int main() {
while (~scanf("%d %d", &N, &M) && (N + M)) {
Init();
int cnt, t1, t2;
for (int i = 1; i <= M; i++) {
scanf("%d", &cnt);
scanf("%d", &t1);
for (int j = 2; j <= cnt; j++) {
scanf("%d", &t2);
Union(t1, t2);
}
}
// for (int i = 0; i < 20; i++) cout << par[i] << " ";
// cout << endl;
int ans = 0;
int temp = Query(0);
for (int i = 1; i < N; i++) {
if (Query(i) == temp) ans++;
}
printf("%d\n", ans + 1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: