Advertisement
wym1111

Untitled

Mar 23rd, 2024
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 2e5 + 10;
  5.  
  6. int n, a[N];
  7. int vis[N];
  8. int dep[N];
  9.  
  10. int ans = N;
  11.  
  12. void dfs (int x, int d, int v) {
  13. //  cout << x << ' ' << d << ' ' << dep[x] << endl;
  14.     if (vis[x]) {
  15.         if (v == vis[x]) ans = min(ans, d - dep[x]);
  16.         return;
  17.     }
  18.     vis[x] = v;
  19.     dep[x] = d;
  20.     dfs(a[x], d + 1, v);
  21. }
  22.  
  23. int main () {
  24.     cin >> n;
  25.     for (int i = 1; i <= n; i ++) {
  26.         cin >> a[i];
  27.     }
  28.     for (int i = 1; i <= n; i ++) {
  29.         if (vis[i]) continue;
  30.         dfs(i, 1, i);
  31.     }
  32.     cout << ans << endl;
  33.     return 0;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement