Sum of Next ValuesEasy

Sum of Next Values

EasyPractice library · +10 XPlinked structuresarrayssimulation

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.

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
Output
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

Input
3
5 1 10
2 0 1
Output
16

Starts at index 0 (value 5). Next is 2 (value 10). Next is 1 (value 1). Sum = 5+10+1 = 16.

Hints