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.
A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.
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 0Sample Output
4 1
1
#include<iostream> using namespace std; #define maxn 30002 int fa[maxn]; int find(int x) { if(x==fa[x]) return x; //不要写成return 0; 别问我怎么知道!!!!! int r=fa[x]; while(r!=fa[r]) r=fa[r]; return fa[r]; } void link(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) { fa[fx]=fy; //将x的父节点连接到y的父节点上 } } int main() { int n,m,k; int sum; while(cin>>n>>m&&(n+m)) { sum=0; for(int i=0;i<n;i++) //初始化将每个节点的父节点初始化为自身 { fa[i]=i; } for(int i=0;i<m;i++) { cin>>k; int one,another; cin>>one; //输入该行第一个数 for(int i=1;i<=k-1;i++) { cin>>another; if(fa[one]!=fa[another]) link(one,another); //将第一个数与其他k-1个数连接 } } int xx=find(0); for(int i=0;i<n;i++) { if(find(i)==xx) { sum++; } } cout<<sum<<endl; } return 0; }