This page is still under construction.

Parts of this page are still being built. What you see may change.

Forensic

Time limit2sMemory limit512 MB

Summary
Change at most one array entry so the pointer chain starting at index 0 visits as many distinct indices as possible before reaching -1.
Level

Medium7 of 10

Topics
Graph, DFS
Solved
No attempts yet

Problem

Example array A

The table above shows the content of an array AA, with the indices in the top row. The array stores the pointers of a singly linked list, and here a pointer is just an integer value. The pointer of the first node sits in A[0]A[0], so the value of A[0]A[0] is the location of the second node. The pointer of the second node sits in A[A[0]]A[A[0]], the pointer of the third node sits in A[A[A[0]]]A[A[A[0]]], and so on. A pointer with value −1-1 is the end of the linked list. In the example above, A[0]A[0] is 2, so the second pointer sits in A[2]A[2]. The value of A[2]A[2] is 4, so the third pointer sits in A[4]A[4]. The value of A[4]A[4] is −1-1, so no further node follows. The sequence of pointers is written below, and this linked list has 3 nodes.

A[0]=2→A[2]=4→A[4]=−1A[0] = 2 \rightarrow A[2] = 4 \rightarrow A[4] = -1

You received the entries of an array like this, and you were told that one entry was replaced. Neither the position of that entry nor its new value is known. The new value may equal the original one, in which case the array is unchanged. As a forensic expert you want to recover the original array, so you want to modify a single entry and make the modified array represent a linked list with as many nodes as possible. Consider the example above.

  • Changing A[4]A[4] to 6 gives a linked list of 4 nodes.
  • Changing A[0]A[0] to 7 gives a linked list of 4 nodes.
  • Changing A[0]A[0] to 9 gives no valid linked list.
  • Changing A[2]A[2] to 7 gives a linked list of 5 nodes.

Among all changes to one entry, including changing nothing, the recovered list of 5 nodes is the largest. So the original entry of A[2]A[2] was probably 7. Compute the size of the largest linked list that can be recovered this way.

Input

The first line contains NN, the size of the array. The second line contains the NN entries of the array separated by spaces, starting from A[0]A[0]. Every entry is an integer that is at least −1-1 and less than NN.

Output

Print the number of nodes in the largest recovered linked list.

Examples5

  1. Example 1

    Input
    10
    2 5 4 4 -1 1 -1 3 0 8
    
    Expected output
    5
    
  2. Example 2

    Input
    4
    0 0 0 0
    
    Expected output
    1
    
  3. Example 3

    Input
    6
    1 2 3 4 5 -1
    
    Expected output
    6
    
  4. Example 4

    Input
    10
    2 5 4 4 0 1 -1 3 0 8
    
    Expected output
    4
    
  5. Example 5

    Input
    10
    2 5 4 4 -1 1 -1 6 0 8
    
    Expected output
    5