Problem 509
Array Nesting
Medium · 20 pts · Array, Depth-First Search
Problem
The array is a permutation of 0 to N - 1. Starting at an index k, build the set S(k) = { A[k], A[A[k]], A[A[A[k]]], ... }, stopping just before an element would repeat. Find the size of the largest such set over all starting indices. Following A from any index walks around a cycle of the permutation, so the answer is the length of its longest cycle; mark visited indices so each one is followed only once.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. The values are a permutation of 0 to N - 1.
Output
Print the size of the largest set.
Constraints
1 <= N <= 100000; A is a permutation of 0 .. N-1
Example input
7 5 4 0 3 1 6 2
Example output
4
Explanation
In 5 4 0 3 1 6 2, starting at index 0 visits A[0] = 5, A[5] = 6, A[6] = 2 and A[2] = 0, and then 5 would repeat. That set has 4 elements, the largest possible.