【POJ 1611】 The Suspects(并查集练习)

时间:2023-02-13 22:34:40

The Suspects


Description
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.


Input
The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space.
A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.

Output
For each case, output the number of suspects in one line.


Sample Input
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
Sample Output
4
1
1


题意:

非典正在肆虐。大学内有很多小组。一组中有一个患者, 组内的所有成员就都是患者。共有n人,规定每个学生的序号为0~n-1,且只有序号0是患者而且一定是患者。每组学生的序号已知。问总共有多少人患病?
输入总人数N和总组数M,接下来M行,第一个数为组员数t,之后t个数表示组员序号(在整个群体中的序号)。


思路:

  • 首先分析一下第二组样例。样例中没有0,并不是没有人患病。而是0号患病,但没有出现在任何组中。故不会传播。但患病人数为1。

    Input
    200 2
    1 5
    5 1 2 3 4 5
    Output
    1

  • 裸题并查集。注意处理方法。for(int i=0;i<t-1;i++) join(ar[i],ar[i+1]); 相邻数据两两调用join构建联通块。前面几题联通块的构建都是诸如1,2;2,3;3,4的数据,因此此处也需要作类似处理。(构建联通块,为了找到每一组的根结点).
    最后找0所在组的根结点,遍历所有人寻找其根结点,比较相等则患病人数+1。


代码示例:

#include<iostream>
#include<cstring>
using namespace std;
#define MAX 30005
int pre[MAX];
int ar[MAX];
int Find(int x)
{
int r=x;
while(r!=pre[r])
{
r=pre[r];
}
int i=x,j;
while(i!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}

int join(int x,int y)
{
int Fx=Find(x),Fy=Find(y);
if(Fx!=Fy)
pre[Fx]=Fy;
}
int main()
{
int N,M;
while(cin>>N>>M&&(M||N))
{
for(int i=0;i<N;i++) pre[i]=i;
while(M--)
{
int t;
cin>>t;
for(int i=0;i<t;i++) cin>>ar[i];
for(int i=0;i<t-1;i++) join(ar[i],ar[i+1]);
}
int ans=0;
for(int i=0;i<N;i++)
{
if(Find(i)==Find(0))
ans++;
}
cout<<ans<<endl;
}

return 0;
}