#include <iostream>
#include <cstdio>
using namespace std;
const int N = 200010;
int n, fa[N], ans = 0x3f3f3f3f;
int get (int x, int &cnt) { //cnt记录环的长度 cnt ++;if (fa[x] == x) return x;else return get(fa[x], cnt);
}
int main () {scanf("%d", &n);for (int i = 1; i <= n; i ++)fa[i] = i;for (int i = 1; i <= n; i ++) {int cnt = 0, f;scanf("%d", &f);if (get(f, cnt) == i) {ans = min(ans, cnt); //维护最小的环 }elsefa[i] = f;}printf("%d", ans);return 0;
}
这个解法是真的帅–并查集
overover