Advertisement
newb_ie

Untitled

Nov 1st, 2021
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. bool visited[1010];
  5. int a[1010];
  6. int res = 0;
  7.  
  8. void dfs (int idx) {
  9. visited[idx] = true;
  10. idx = a[idx];
  11. if (visited[idx]) {
  12. res = idx;
  13. return;
  14. } else {
  15. dfs(idx);
  16. }
  17. }
  18.  
  19. int main () {
  20. ios::sync_with_stdio(false);
  21. cin.tie(nullptr);
  22. cout.tie(nullptr);
  23. int n;
  24. cin >> n;
  25. for (int i = 1; i <= n; ++i) cin >> a[i];
  26. for (int i = 1; i <= n; ++i) {
  27. for (int j = 1; j <= n; ++j) {
  28. visited[j] = false;
  29. }
  30. res = -1;
  31. dfs(i);
  32. cout << res << ' ';
  33. }
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement