WEEK 6 B with a mask

topic:

The new corona virus pneumonia (Corona Virus Disease 2019, COVID-19), referred to as "new coronary pneumonia", refers to pneumonia caused by 2019 new coronavirus infection.
If an infected person enters a group, then this group needs to be isolated!
Little A student was diagnosed with a new crown infection and did not wear a mask! ! ! ! ! !
Dangerous! ! !
Time is running out! ! ! !
You need to find all the students who have been in direct or indirect contact with Xiao A as soon as possible to isolate them to prevent a wider spread.
As we all know, student communication may be divided into small groups, and a student may participate in multiple small groups at the same time.
Please write a program to solve it! wear mask! !

Input

Multiple sets of data, for each set of test data: the
first line is two integers n and m (n = m = 0 indicates the end of input, no need to process), n is the number of students, m is the number of student groups. 0 <n <= 3e4, 0 <= m <= 5e2
student number is 0 ~ n-1
small A number is 0.
Then, m rows, each row has an integer num that is the number of small group personnel. Then there are num integers representing the students of this small group.

Output

Output the number of people to be isolated, the answer output of each group of data occupies 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

Ideas:

This question adopts the idea of ​​checking and collecting, according to whether the students have direct or indirect contact, the students are merged. The students of the same group are the same set. If the students of the two groups have intersection, the two sets are merged and each For the number of students in the collection, just output the number of students in the collection where student 0 is located.

Code:

#include <iostream>

using namespace std;

const int maxn = 3e4 + 5;
int par[maxn], rnk[maxn];

void init(int n)
{
	for (int i = 0; i < n; i++)
		par[i] = i, rnk[i] = 1;
}
int find(int x)
{
	if (par[x] == x)
		return x;
	else
		return par[x] = find(par[x]);
}
bool unite(int x, int y)
{
	x = find(x), y = find(y);
	if (x == y)
		return false;
	par[x] = y;
	rnk[y] += rnk[x];
	return true;
}


int main()
{
	int m, n;
	while (scanf("%d%d",&n,&m)&&!(n==0&&m==0))
	{
		init(n);
		while (m--)
		{
			int num, last = -1;
			scanf("%d", &num);
			for (int i = 0; i < num; i++)
			{
				int p;
				scanf("%d", &p);
				if (last != -1)
					unite(p, last);
				last = p;
			}
		}
		printf("%d\n", rnk[find(0)]);
	}
    return 0; 
}
Published 32 original articles · Likes0 · Visits 680

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/105253696