Rigging the Draw

Given a functional graph on N positions, find the smallest k between 2 and 2e9 such that applying the map k times sends every position away from itself.

Medium6GraphSimulationNumber theoryBrute forceNo attempts yetTime limit1sMemory limit256 MB

Problem

For the school festival, Kusagwa built a game that charges an entry fee and lets many people play at once. The heart of the game is a draw machine. The machine has positions 11 through NN arranged in a circle, and every position has one hole on top and one hole underneath. A marble dropped into a top hole travels through fixed passages inside and falls out of one of the bottom holes.

The rules are simple. NN people gather and one person stands at each position from 11 to NN. Kusagwa drops one marble into the top hole of person 11, then person 22, and so on through person NN, and watches where each marble comes out. If a marble comes out of the bottom hole of the same position, nothing happens. If it comes out anywhere else, that person wins a prize. There is one catch: if every marble comes out at a position other than its own, the round is a jackpot and nobody wins a prize.

People who know nothing about the inside of the machine think the prizes come easily, but Kusagwa did the arithmetic. The marbles look random, and in fact each one lands exactly where the passages send it.

Building the first machine was very hard, copying it is easy. Attaching identical copies underneath gives what looks like one larger machine with a longer, flashier path, while the outcome stays exactly what Kusagwa chose. In a stack of kk machines, a marble dropped at position ii moves to position JiJ_i in the first machine, to position JJiJ_{J_i} in the second, and falls out at the position reached after kk such moves.

For example, the machine J=(2,1,4,3)J = (2, 1, 4, 3) already pays off for Kusagwa on its own. Stacking two copies sends every marble back to its own position and nothing happens, and stacking three copies again sends every marble somewhere else.

Kusagwa wants to stack at least two machines to make the game tense. Person 11, then person 22, and so on watch their marbles come out somewhere else and get excited, and the moment person NN's marble also lands elsewhere, Kusagwa plans to announce that it really did happen. Given one machine, find how many copies Kusagwa has to stack to come out ahead.

Input

The first line contains an integer NN (1N1061 \le N \le 10^6).

The second line contains NN integers J1,J2,,JNJ_1, J_2, \dots, J_N separated by spaces (1JiN1 \le J_i \le N). JiJ_i is the position where a marble dropped at position ii lands after passing through one machine. The JiJ_i are not guaranteed to be distinct.

Output

Print the smallest kk that makes every person's marble land at a position other than their own. kk must satisfy 2k2×1092 \le k \le 2 \times 10^9. If no such kk exists in that range, print -1.