poj1611 并查集

时间:2021-01-07 03:14:06

题目链接:http://poj.org/problem?id=1611

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector> #define maxn 30050
#define INF 0x3f3f3f
using namespace std;
int pa[maxn]; int find(int x){
return x == pa[x] ? x : pa[x] = find(pa[x]);
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)){
if(!n && !m) break;
for(int i=;i<n;i++) pa[i] = i; for(int i=;i<=m;i++){
int k;
scanf("%d",&k);
if(!k) continue;
int a,b;
scanf("%d",&a);
k--;
while(k--){
scanf("%d",&b);
int ta = find(a);
int tb = find(b);
if(ta != tb){
if(ta < tb) pa[tb] = ta;
else pa[ta] = tb;
}
}
}
int ans = ;
for(int i=;i<n;i++){
if(find(i) == ) ans++;
}
printf("%d\n",ans);
}
}