Advertisement
a53

Planete

a53
Feb 14th, 2022 (edited)
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define N 200001
  3. using namespace std;
  4. int n,t[N],dp[N],st[N],k,st2[N],k2;
  5. bool vz[N],sta[N];
  6.  
  7. void dfs(int x)
  8. {
  9. st[++k]=x;
  10. sta[x]=vz[x]=true;
  11. if(!vz[t[x]])
  12. {
  13. dfs(t[x]);
  14. if(!dp[x])
  15. dp[x]=dp[t[x]]+1,sta[st[k--]]=false;
  16. }
  17. else
  18. {
  19. if(sta[t[x]])
  20. {
  21. k2=0;
  22. while(st[k]!=t[x])
  23. sta[st[k]]=false,st2[++k2]=st[k--];
  24. sta[st[k]]=false,st2[++k2]=st[k--];
  25. for(int j=1;j<=k2;++j)
  26. dp[st2[j]]=k2;
  27. }
  28. else
  29. dp[x]=dp[t[x]]+1,sta[st[k]]=false,--k;
  30. }
  31. }
  32.  
  33. int main()
  34. {
  35. ios_base::sync_with_stdio(false);
  36. cin.tie(nullptr);
  37. cin>>n;
  38. for(int i=1;i<=n;++i)
  39. cin>>t[i];
  40. for(int i=1;i<=n;++i)
  41. if(!dp[i])
  42. dfs(i);
  43. for(int i=1;i<=n;++i)
  44. cout<<dp[i]<<' ';
  45. return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement