题目描述
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of 𝑛n students doing yet another trick.
Let's assume that all these students are numbered from 11 to 𝑛n. The teacher came to student 𝑎a and put a hole in his badge. The student, however, claimed that the main culprit is some other student 𝑝𝑎pa.
After that, the teacher came to student 𝑝𝑎pa and made a hole in his badge as well. The student in reply said that the main culprit was student 𝑝𝑝𝑎ppa.
This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.
After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.
You don't know the first student who was caught by the teacher. However, you know all the numbers 𝑝𝑖pi. Your task is to find out for every student 𝑎a, who would be the student with two holes in the badge if the first caught student was 𝑎a.
Input
The first line of the input contains the only integer 𝑛n (1≤𝑛≤10001≤n≤1000) — the number of the naughty students.
The second line contains 𝑛n integers 𝑝1p1, ..., 𝑝𝑛pn (1≤𝑝𝑖≤𝑛1≤pi≤n), where 𝑝𝑖pi indicates the student who was reported to the teacher by student 𝑖i.
Output
For every student 𝑎a from 11 to 𝑛n print which student would receive two holes in the badge, if 𝑎a was the first student caught by the teacher.
Examples
input
Copy
3 2 3 2
output
Copy
2 2 3
input
Copy
3 1 2 3
output
Copy
1 2 3 s
思路
- 从每个点开始dfs, vis数组记录每个点被遍历的次数, 如果次数大于等于2,即被第二次遍历到, 此时的点的编号就是答案,
- 否则根据p数组跳转到被指认的点
代码
#include<iostream>
#include<cstring>
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);i++)
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
typedef pair<int, int> PLL;
typedef long long ll;
const int N = 2e5+5;
const int INF = 0x3f3f3f3f;
int readint(){
int x;scanf("%d",&x);return x;
}
int n, p[1001], vis[1001];
int ans;
void dfs(int x) {
vis[x]++;
if(vis[x] >= 2) {
ans = x;
return;
} else {
dfs(p[x]);
}
}
int main()
{
n = readint();
_rep(i, 1, n) p[i] = readint();
_rep(i, 1, n) {
dfs(i);
memset(vis, 0, sizeof(vis));
printf("%d ", ans);
}
return 0;
}