简单并查集
View Code
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; #define maxn 30005 int n, m; int father[maxn]; int stk[maxn]; void init() { for (int i = 0; i < n; i++) father[i] = i; } int getanc(int a) { int top = 0; while (father[a] != a) { stk[top++] = a; a = father[a]; } while (top) father[stk[--top]] = a; return a; } void merge(int a, int b) { int x = getanc(a); int y = getanc(b); father[x] = father[y]; } void input() { int k; for (int i = 0; i < m; i++) { scanf("%d", &k); if (k == 0) continue; int a, b; scanf("%d", &a); for (int j = 1; j < k; j++) { scanf("%d", &b); merge(a, b); } } } int work() { int ret = 0; for (int i = 0; i < n; i++) if (getanc(i) == getanc(0)) ret++; return ret; } int main() { //freopen("t.txt", "r", stdin); while (scanf("%d%d", &n, &m), n | m) { init(); input(); printf("%d\n", work()); } return 0; }