POJ 1611 The Suspects(简单并查集)
2017-07-20 08:53
267 查看
Description
有n名学生(编号0~n-1)分成了m组,其中学生0感染了病毒,这种病毒极易传播,两人只要接触就会传播,一人感染全组感染,问共有多少名学生会感染这种病毒?Input
多组用例,每组用例第一行为两个整数n和m表示学生人数和组数,之后m行每行首先输入该组学生人数num,然后输入num个整数表示该组学生的编号,以 0 0结束输入Output
对于每组用例,输出被感染学生的数量Sample Input
100 42 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
Solution
将每一行数据进行Unite(),后查找与
0元素同一个集合的元素个数即可。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int pre[30010]; void init(int len) { // memset(pre, -1, sizeof(int) * len); for (int i = 0; i <= len; i++) { pre[i] = i; } } int find(int x) { if (pre[x] == x) { return x; } return pre[x] = find(pre[x]); } void join(int i, int j) { int iRoot = find(i); int jRoot = find(j); if (iRoot != jRoot) { pre[jRoot] = iRoot; } } int main() { int id, lines; while (scanf("%d%d", &id, &lines) && (id || lines)) { init(id); while (lines--) { int num_stu, stu1, pre_stu; scanf("%d", &num_stu); for (int i = 0; i < num_stu; i++) { scanf("%d", &stu1); if (i == 0) { pre_stu = stu1; } join(pre_stu, stu1); pre_stu = stu1; } } int ans = 1; for (int i = 1; i <= id; i++) { if (find(0) == find(i)) { ans++; } } cout << ans << endl; } }
相关文章推荐
- POJ1611——The Suspects
- [并查集]POJ 1611 The Suspects
- POJ1611:The Suspects
- POJ 1611 The Suspects
- poj 1611 The Suspects
- poj 1611.The Suspects
- Poj:1611 The Suspects
- POJ1611 The Suspects (并查集)
- POJ 1611 The Suspects
- POJ 1611 The Suspects
- poj 1611 The Suspects (并查集)
- poj 1611 The Suspects
- POJ 1611 The Suspects
- 【poj】-1611-The Suspects(找到需要的根,再找所有根为此的树枝)
- poj union_find相关之1611 The Suspects
- POJ 1611 The Suspects
- POJ-1611 The Suspects (并查集模板题)
- POJ 1611 The Suspects(简单模板题)
- POJ-1611 The Suspects
- POJ 1611 The Suspects(并查集)