题目链接: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=0;i<n;i++) pa[i] = i; for(int i=1;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 = 1; for(int i=1;i<n;i++){ if(find(i) == 0) ans++; } printf("%d ",ans); } }