Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- bool visited[1010];
- int a[1010];
- int res = 0;
- void dfs (int idx) {
- visited[idx] = true;
- idx = a[idx];
- if (visited[idx]) {
- res = idx;
- return;
- } else {
- dfs(idx);
- }
- }
- int main () {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int n;
- cin >> n;
- for (int i = 1; i <= n; ++i) cin >> a[i];
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= n; ++j) {
- visited[j] = false;
- }
- res = -1;
- dfs(i);
- cout << res << ' ';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement