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.
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
4 1 1
题意:n个学生分属m个团体,(0 < n <= 30000 , 0 <= m <= 500)一个学生可以属于多个团体。
一个学生疑似患病则它所属的整个团体都疑似患病。
已知0号学生疑似患病,以及每个团体都由哪些学生构成,求一共多少个学生疑似患病。
//看了一位大佬的博客,秒懂并查集,初学可以去看看,写的太好了 //附地址:https://blog.csdn.net/niushuai666/article/details/6662911 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<cstring> #include<stdio.h> #include<algorithm> #include<map> #include<queue> #include<set> #include <sstream> #include<vector> #include<cmath> #include<stack> #include<time.h> #include<ctime> using namespace std; #define inf 1<<30 #define eps 1e-7 #define LD long double #define LL long long #define maxn 100000005 int pre[100009] = {}; int rootsearch(int root)//寻找这个数的领导 { int son; son = root; while (root != pre[root])//这个数不是领导,继续往下找 { root = pre[root]; } while (son != root)//路径压缩,把找到的下级数全部指向最高领导 { int temp = pre[son]; pre[son] = root; son = temp; } return root;//返回最高领导 } int a[30020] = {}; int main() { int n, m, k, sum; while (scanf("%d%d", &n, &m), n + m) { sum = 0; for (int i = 0; i < n; i++)//一开始,自己是自己的领导 { pre[i] = i; } while (m--) { int root1, root2; scanf("%d", &k); scanf("%d", &a[0]); for (int i = 1; i < k; i++) { scanf("%d", &a[i]); root1 = rootsearch(a[0]); root2 = rootsearch(a[i]); if (root1 != root2)//两个人的最高领导不同 { pre[root1] = root2;//把第一个集合的最高领导改为第二个集合的最高领导 } } } for (int i = 0; i < n; i++) { if (rootsearch(i) == pre[0])//第i个的最高领导和第0个的最高领导一样 { sum++;//不幸者加一 } } printf("%d\n", sum); } return 0; }
原文:https://www.cnblogs.com/whhh/p/13035014.html