Sum of Next Values
You are given an array next_idx of size N. The element next_idx[i] indicates the index of the next element to visit. You start at index 0. Follow the next_idx array, visiting elements, and sum their values. The array contains N integers, where the i-th integer is the value at index i. The indices are 0-based. You will always visit exactly N elements before the sequence ends. Print the total sum.
Input
The first line contains an integer N. The second line contains N space-separated integers representing the values at each index. The third line contains N space-separated integers representing the next_idx array.
Output
A single integer: the sum of the N values visited.
Constraints
1 <= N <= 1000. All values and indices will be non-negative.
Example 1
5 10 20 30 40 50 1 2 3 4 0
150
Starts at index 0 (value 10). Next is 1 (value 20). Next is 2 (value 30). Next is 3 (value 40). Next is 4 (value 50). Sum = 10+20+30+40+50 = 150.
Example 2
3 5 1 10 2 0 1
16
Starts at index 0 (value 5). Next is 2 (value 10). Next is 1 (value 1). Sum = 5+10+1 = 16.
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 0
3 5 1 10 2 0 1