这道题是union-find的应用,就是找到和0在一个集合的所有元素个数。
1611 | Accepted | 372K | 16MS | C++ | 1636B |
/*
ID: thestor1
LANG: C++
TASK: poj1611
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
const int MAXN = 30000;
void makeset(const int N, std::vector<int> &parent, std::vector<int> &rank)
{
for (int u = 0; u < N; ++u)
{
parent[u] = u;
rank[u] = 0;
}
}
int find(int u, std::vector<int> &parent)
{
if (parent[u] != u)
{
parent[u] = find(parent[u], parent);
}
return parent[u];
}
void union_set(int u, int v, std::vector<int> &parent, std::vector<int> &rank)
{
int ru = find(u, parent);
int rv = find(v, parent);
if (ru == rv)
{
return;
}
if (rank[ru] < rank[rv])
{
parent[ru] = rv;
}
else if (rank[rv] < rank[ru])
{
parent[rv] = ru;
}
else
{
parent[ru] = rv;
rank[rv]++;
}
}
int main()
{
std::vector<int> parent(MAXN);
std::vector<int> rank(MAXN);
int n, m;
while (scanf("%d%d", &n, &m) && n != 0)
{
makeset(n, parent, rank);
for (int i = 0; i < m; ++i)
{
int k;
scanf("%d", &k);
if (k == 0)
{
continue;
}
int u;
scanf("%d", &u);
for (int j = 1; j < k; ++j)
{
int v;
scanf("%d", &v);
union_set(u, v, parent, rank);
}
}
int cnt = 1;
for (int i = 1; i < n; ++i)
{
if (find(0, parent) == find(i, parent))
{
cnt++;
}
}
printf("%d\n", cnt);
}
return 0;
}