#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n, deg[N], to[N];
bool vis[N], can[N];
queue<int> q;
void _main() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> to[i], deg[to[i]]++;
for (int i = 1; i <= n; i++) {
if (deg[i] == 0) q.emplace(i);
}
int res = 0;
while (!q.empty()) {
int u = q.front(), v = to[u]; q.pop();
vis[u] = true;
if (can[u]) {
if (--deg[v] == 0) q.emplace(v);
} else {
if (!can[v]) res++, q.emplace(v);
can[v] = true;
}
}
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;
int cnt = 0;
for (int j = i; !vis[j]; j = to[j]) cnt++, vis[j] = true;
res += cnt / 2;
}
cout << res;
} signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr), cerr.tie(nullptr);
int t = 1;
// cin >> t;
while (t--) _main();
return 0;
}
这是本蒟蒻的 AC 代码。
将 j=to[j] 改为 j=to[i],洛谷 90pts,校内 oj 直接 AC,且自己拍的时候发现正确率很高,平均每 20 组才 WA 一次,想问下各位大佬这么离谱的错误为什么正确率这么高。