Description
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 1 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≤n≤1000) — the number of the naughty students.
The second line contains n integers p1, …, pn (1≤pi≤n), where pi indicates the student who was reported to the teacher by student i.
Output
For every student a from 1 to n print which student would receive two holes in the badge, if a was the first student caught by the teacher.
Sample Input
3
2 3 2
Sample Output
2 2 3
核心思想:
每个点有且只有一个后继。
枚举每一个点当作dfs起点,对于起点 i 的dfs:
每搜索完一个点就将此点标记,当搜索到被标记的点的时候,此点就是点 i 的替罪羊。
详见代码。
代码如下:
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=1e3+20;
int a[N];
bool vis[N];
int dfs(int x)
{
if(vis[x])
return x;
vis[x]=1;
//用re存一下返回值,清除vis标记后再返回
int re=dfs(a[x]);
vis[x]=0;
return re;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<n;i++)
printf("%d ",dfs(i));
printf("%d\n",dfs(n));
return 0;
}