POJ 1611 The Suspects
题目的意思大致是说,同学之间有时会有一些小团体,现在已知0号同学已经感染了sars,那么跟他平时接触多的同学(团体内的所有人),都将被列为感染者,现在给出学生总数N以及团体总数M以及团体内部成员的具体编号,问总共有多少同学为感染者。
经典的并查集问题,运用并查集判断各个元素所处的集合,将于0号元素所处集合相同的元素累计即可得解,数据范围N<=30000,M<=500,故感觉数据规模不是很大,所以并查集部分并没有加上秩,没有加按秩合并的优化,仅仅加上了路径压缩。
代码如下:
#include <iostream> using namespace std; #define MAXN 30002 int N , M , K , s , e , ans; int root[MAXN]; int getroot(int x) { int y = x, temp; while (root[x] != x) x = root[x]; temp = x; x = y; while (root[x] != x) { x = root[x]; root[x] = temp; } return temp; } int main () { while (cin >> N >> M && (N || M)) { for (int i = 0;i < N;i++) root[i] = i; for (int i = 0;i < M;i++) { cin >> K >> s; for (int j = 1;j < K;j++) { cin >> e; int f1 = getroot(s) , f2 = getroot(e); root[f2] = f1; } } int t = getroot(0); ans = 0; for (int i = 0;i < N;i++) if (t == getroot(i)) ans ++; cout << ans << endl; } return 0; }
测试结果如下: