All problems

Problem 945

Longest Cycle in a Graph

Hard · 30 pts · Graph, Depth-First Search, Topological Sort

Problem

A directed graph has N nodes numbered 0 to N - 1, and every node has at most one outgoing edge: EDGES[i] is the node that i points to, or -1. Find the length of the longest cycle, or print -1 if the graph has no cycle. Walk from every unvisited node, recording the step at which each node was first reached on the current walk; meeting a node from the current walk again closes a cycle whose length is the difference of the steps.

Input

The first line contains N. The second line contains EDGES[0..N-1].

Output

Print the length of the longest cycle, or -1.

Constraints

2 <= N <= 100000; -1 <= EDGES[i] < N; EDGES[i] != i

Example input

5
3 3 4 2 3

Example output

3

Explanation

With EDGES = 3 3 4 2 3, the walk from 2 goes 2 → 4 → 3 → 2, a cycle of length 3, and there is no other cycle. So the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Employees to Be Invited to a Meeting Next: Find Closest Node to Given Two Nodes