Next Element in Array
You are given two arrays: values and next_indices. The values array contains N integers. The next_indices array also contains N integers, where next_indices[i] indicates the index of the next element in a sequence starting from index i. The sequence is guaranteed to be a simple linked list (no cycles, no branching, starts at index 0). You are also given a target value X. Find and print the value of the element that comes immediately after the first occurrence of X in the values array. If X is not present in the values array, or if X is the last element in the sequence, print -1.
Input
The first line contains an integer N (1 <= N <= 1000). The second line contains N space-separated integers for the values array. The third line contains N space-separated integers for the next_indices array. The fourth line contains the target integer X.
Output
Print a single integer: the value of the element immediately following X, or -1 if X is not found or is the last element.
Constraints
1 <= N <= 1000 -10^9 <= values[i] <= 10^9 0 <= next_indices[i] < N The sequence starting from index 0 is a valid linked list (no cycles). Index 0 is the head of the list.
Example 1
5 10 20 30 40 50 1 2 3 4 -1 30
40
X=30 is at index 2. Its next index is 3. The value at index 3 is 40.
Example 2
3 5 15 25 1 2 -1 25
-1
X=25 is at index 2, which is the last element. Its next index is -1. Output is -1.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 10 20 30 40 50 1 2 3 4 -1 30
3 5 15 25 1 2 -1 25