bingxuan9112

DFS

Sep 29th, 2019
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. const int N = 2025;
  5.  
  6. int n, p[N], vis[N], ans;
  7. vector<int> g[N];
  8. void dfs(int i, int dep) {
  9.     ans = max(ans,dep);
  10.     vis[i] = 1;
  11.     for(int j:g[i]) if(!vis[j]) dfs(j, dep+1);
  12. }
  13. int main() {
  14.     cin >> n;
  15.     for(int i = 1; i <= n; i++) cin >> p[i];
  16.     for(int i = 1; i <= n; i++) {
  17.         if(p[i] != -1) g[p[i]].push_back(i);
  18.     }
  19.     for(int i = 1; i <= n; i++) if(!vis[i]) dfs(i,1);
  20.     cout << ans << '\n';
  21. }
Advertisement
Add Comment
Please, Sign In to add comment