Rigging the Draw
Time limit1sMemory limit256 MB
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.
- Level
Medium6 of 10
- Topics
- Graph, Simulation, Number theory, Brute force
- Solved
- No attempts yet
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 through 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. people gather and one person stands at each position from to . Kusagwa drops one marble into the top hole of person , then person , and so on through person , 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 machines, a marble dropped at position moves to position in the first machine, to position in the second, and falls out at the position reached after such moves.
For example, the machine 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 , then person , and so on watch their marbles come out somewhere else and get excited, and the moment person '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 ().
The second line contains integers separated by spaces (). is the position where a marble dropped at position lands after passing through one machine. The are not guaranteed to be distinct.
Output
Print the smallest that makes every person's marble land at a position other than their own. must satisfy . If no such exists in that range, print -1.