Algorithm
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 1e3 + 1;
int n, p[N];
bool vis[N];
int main() {
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%d", p + i), --p[i];
for(int i = 0; i < n; ++i) {
memset(vis, false, sizeof vis);
vis[i] = true;
int cur = p[i];
while(!vis[cur]) {
vis[cur] = true;
cur = p[cur];
}
printf("%d ", cur + 1);
}
puts("");
return 0;
}
Copy The Code &
Try With Live Editor
Input
3
2 3 2
2 3 2
Output
2 2 3
Demonstration
Codeforces Solution-B. Badge-Solution in C, C++, Java, Python,Badge-Solution,Codeforces Solution