Find Element After StepsEasy

Find Element After Steps

EasyPractice library · +10 XPlinked structuressimulationarrays

You are given a linked list represented using two arrays: next_val and pos. The array next_val stores the value of the next node, and pos stores the index of the next node. The first node is always at index 0. Starting from the first node (index 0), traverse the linked list for exactly K steps. Print the value of the node you land on after K steps. If K is 0, print the value of the starting node.

Input

The first line contains an integer N (1 <= N <= 1000), the number of nodes. The second line contains N integers, representing the next_val array. The third line contains N integers, representing the pos array. The fourth line contains an integer K (0 <= K <= 1000), the number of steps to take.

Output

Print a single integer: the value of the node after K steps.

Constraints

1 <= N <= 1000 0 <= K <= 1000 0 <= pos[i] < N for all i next_val[i] and K are integers.

Time limit 1 s (native code; slower languages get more)Memory 256 MB12 hidden tests

Example 1

Input
5
10 20 30 40 50
1 2 3 4 0
3
Output
40

Starting at index 0 (value 10), step 1 goes to index 1 (value 20), step 2 to index 2 (value 30), step 3 to index 3 (value 40). Output is 40.

Example 2

Input
3
1 2 3
1 2 0
0
Output
1

K is 0, so we print the value of the starting node (index 0), which is 1.

Hints