题目链接:点击打开链接
简单的并查集,水题
// POJ 1611 The Suspects.cpp
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class DisjointSet {
private:
int n;
vector<int> fa, rank;
public:
DisjointSet(int n) :n(n),fa(n), rank(n) {
for (int i = 0; i < n; i++) {
fa[i] = i;
rank[i] = 0;
}
}
int getFather(int x) {
return fa[x] = (fa[x] == x ? x : getFather(fa[x]));
}
void merge(int x, int y) {
int a = getFather(x);
int b = getFather(y);
if (a == b) {
return;
}
if (rank[a] < rank[b]) {
fa[a] = b;
}
else {
fa[b] = a;
if (rank[a] == rank[b]) {
rank[a]++;
}
}
}
int count() {
int cnt = 0;
int re = getFather(0);
for (int i = 0; i < n; i++) {
if (getFather(i) == re) {
cnt++;
}
}
return cnt;
}
};
int main(){
int n, m, k, fir, te;
while (scanf("%d%d", &n, &m) != EOF) {
if (!n && !m) break;
DisjointSet s(n);
for (int i = 0; i < m; i++) {
scanf("%d", &k);
if (k) scanf("%d", &fir);
for (int j = 0; j < k - 1; j++) {
scanf("%d", &te);
s.merge(fir, te);
}
}
cout << s.count() << endl;
}
return 0;
}