https://www.luogu.com.cn/problem/P2661
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int fa[maxn]; int cnt,n,a,ans = 0x3f3f3f3f; int find(int x,int &cnt){ cnt++; if(x == fa[x]) return x; return find(fa[x],cnt); } int main(){ // freopen("in","r",stdin); ios::sync_with_stdio(0); cin >> n; for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 1; i <= n; i++){ cin >> a; cnt = 0; if(find(a,cnt) == i) ans = min(ans,cnt); else fa[i] = a; } cout << ans; return 0; }
cnt的设数值要注意一下,0x3fWA了