Linked List Path SumMedium

Linked List Path Sum

MediumPractice library · +20 XPlinked structureshash mapcycle detection

You are given a sequence of N integers, representing nodes in a linked list. For each node i (0-indexed), the value a[i] represents the index of the next node. The list might contain a cycle. You start at node 0. Calculate the sum of values of nodes visited before the first time a node is visited again. If the list does not form a cycle and ends (a node points to -1), the sum should include all nodes from the start until the end.

Input

The first line contains an integer N. The second line contains N space-separated integers a_0, a_1, ..., a_{N-1}.

Output

Print a single integer: the sum of values of the nodes visited before a node is revisited or the list ends.

Constraints

1 <= N <= 200000. 0 <= a[i] < N or a[i] == -1.

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

Example 1

Input
5
1 2 3 4 1
Output
5

Starts at 0, goes to 1, then 2, then 3, then 4. Next is 1, which is a repeat. Sum = 5 (nodes 0,1,2,3,4).

Example 2

Input
3
1 2 -1
Output
3

Starts at 0, goes to 1, then 2. Next is -1, list ends. Sum = 3 (nodes 0,1,2).

Hints