The Suspects POJ - 1611
思路:并查集模板题,开一个cnt数组维护集合中点的数量,最后输出0号点所在集合中点的数量就可以了
具体代码如下
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 30010;
int n, m;
int p[N], cnt[N];
int group[N];
int find(int x){
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
void unite(int x, int y){
x = find(x), y = find(y);
if(x == y) return;
p[x] = y;
cnt[y] += cnt[x];
}
int main(){
while(~scanf("%d%d", &n, &m)){
if(n == 0 && m == 0) break;
for(int i=0; i<n; ++i){
p[i] = i;
cnt[i] = 1;
}
while(m--){
int n2;
scanf("%d", &n2);
for(int i=0; i<n2; ++i) scanf("%d", &group[i]);
for(int i=1; i<n2; ++i){
unite(group[i-1], group[i]);
}
}
printf("%d\n", cnt[find(0)]);
}
return 0;
}