刻录光盘 - 洛谷https://www.luogu.com.cn/problem/P2835
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#define IOS std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const int MAXN = 1e6;
int n;
int pre[MAXN];
void init(int n) {
for (int i = 1; i <= n;i++) {
pre[i] = i;
}
}
int find(int x) {
if (pre[x]==x) {
return x;
}
return pre[x] = find(pre[x]);
}
void unite(int x,int y) {
//x = find(x);
y = find(y);
pre[x] = y;
}
bool vis[250][250];
int main() {
IOS;
cin >> n;
int x;
init(n);
for (int i = 1; i <= n; i++) {
while (cin >> x && x) {
vis[i][x] = true;
}
}
for (int k = 1; k <= n;k++) {
for (int i = 1; i <= n;i++) {
for (int j = 1; j <= n;j++) {
vis[i][j] = vis[i][j] ||(vis[i][k]&&vis[k][j]);
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (vis[i][j]) {
unite(j, i);
}
}
}
int cnt = 0;
for (int i = 1; i <= n;i++) {
if (pre[i]==i) {
cnt++;
}
}
cout << cnt;
return 0;
}