Algorithm
Problem Name: 2 AD-HOC - beecrowd | 1521
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/1521
The Guilty
By Cristhian Bonilha, UTFPR Brazil
Timelimit: 1
Ball of paper war is one of the most classic jokes of the collegiate time, and some people like it so much that they start these wars at the universities. The rules are simple: Aim and hit someone with a ball of paper.
The teachers, on the other side, don't think that this joke is productive, once it takes all the attention from the given class. Even worse, is when a student hits the teacher with the ball of paper.
The teacher this time decided to investigate who participated on the joke, and said it would be enough if at least one of the students was discovered, to serve as an example to the others.
The teacher's investigation process works as follows: it starts asking to a student K if he participated on the joke or, if he didn't participate, that he says who participated. If the K student turned himself, the investigation would end. Otherwise, he would say the number of other student, and the process would repeat with the teacher making the question again to this new student, until some student turned himself.
The teacher provided a list containing the answer of all the students to the given question, and asked your help to find out, if he started the investigation on the student K, who would end turning himself?
It's garanteed that someone will turn himself at the end.
Input
There will be several test cases. Each test case starts with one integer N (3 ≤ N ≤ 50).
Following, there will be N integers ni (1 ≤ ni ≤ N, for all 1 ≤ i ≤ N), where each integer ni means that the student i turned the student ni.
That means, if the third number if 4, then it means that the third student turned the fourth student. If, otherwise, the number is equal to itself, that means he turned himself.
Following there will be one integer K (1 ≤ K ≤ N), indicating who was the student with whom the teacher started the investigation.
The last test case is identified when N = 0, which should not be processed.
Output
For each test case, there must be printed one line, containing one integer, indicating which student ended up turning himself.
Sample Input | Sample Output |
3 |
3 |
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
#define true 1
#define false 0
#define MAXSIZE 60
unsigned short alunos[MAXSIZE];
int main (void)
{
unsigned short i;
unsigned short lista;
while (true)
{
scanf("%hu", &lista);
if (lista == 0)
break;
for (i = 1; i < = lista; ++i)
scanf("%hu", &alunos[i]);
scanf("%hu", &i);
while (alunos[i] != i)
i = alunos[i];
printf("%hu\n", i);
}
}
Copy The Code &
Try With Live Editor
Input
2 3 3
1
3
1 3 2
1
0
Output
1