疫情嚴重,在家玩題,結果第一個就是關於SARS的(大霧...)ios
POJ 1611spa
簡單的並查集code
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn= 3e4+3; const int maxm= 5e2+3; int pa[maxn]; int ans; int rnk[maxn]; int Find(int x) { if (x== pa[x]){ return x; } return pa[x]= Find(pa[x]); } void Merge(int a, int b) { a= Find(a); b= Find(b); if (a== b){ return; } if (rnk[a]< rnk[b]){ pa[a]= b; } else{ pa[b]= a; if (rnk[a]== rnk[b]){ ++rnk[a]; } } } void Init(int n) { memset(rnk, 0, sizeof(rnk)); for (int i= 0; i< n; ++i){ pa[i]= i; } rnk[0]= maxm; ans= 0; } int main() { int n, m, k, x, y; while (EOF!= scanf("%d %d", &n, &m) && (n || m)){ Init(n); for (int i= 0; i< m; ++i){ scanf("%d", &k); scanf("%d", &x); for (int j= 1; j< k; ++j){ scanf("%d", &y); Merge(x, y); } } for (int i= 0; i< n; ++i){ if (0== Find(i)){ ++ans; } } printf("%d\n", ans); } return 0; }