题目描述
Input & Output
Sample
Code
#include <iostream>
#include <vector>
using namespace std;
int Find(int a, vector<int> &father)
{
if (father[a] == a)
return a;
else
return father[a] = Find(father[a], father);
}
void Merge(int a, int b, vector<int> &father)
{
int fa = Find(a, father);
int fb = Find(b, father);
if(fa != fb)
father[fa] = fb;
}
int main()
{
int num_student, num_group;
while (cin >> num_student >> num_group && (num_student || num_group))
{
vector<int> father(num_student, -1);
while (num_group--)
{
int num;
cin >> num;
int first;
for (int i = 0; i < num; i++)
{
int current;
cin >> current;
if (i == 0)
{
if (father[current] == -1)
{
first = current;
father[current] = current;
}
else
{
first = father[current];
}
}
else if (father[current] == -1)
father[current] = father[first];
else
Merge(current, first, father);
}
}
for (int i = 0; i < num_student; i++)
{
if (father[i] != -1)
father[i] = Find(i, father);
}
unsigned sum = 0U;
if (father[0] == -1)
{
cout << 1 << endl;
continue;
}
for (vector<int>::iterator it = father.begin(); it != father.end(); ++it)
{
if (*it == father[0])
sum++;
}
cout << sum << endl;
}
system("pause");
return 0;
}