Counting-Out Rhyme
InterviewTime limit1sMemory limit128 MB
Given the order children leave a Josephus-style circle, find the smallest rhyme length k that produces exactly that leaving order, or report none exists.
- Level
Medium6 of 10
- Topics
- Simulation, Brute force, Math, Implementation
- Solved
- No attempts yet
Problem
Children stand in a circle and play a counting-out game. They are numbered to so that, for each , child stands immediately to the left of child , and child stands immediately to the left of child . In other words, moving leftward around the circle the numbers increase and then wrap back to .
A single round of counting works as follows. Every round uses a rhyme of exactly syllables. The child who begins the round says the first syllable, the child to their left says the second, the next child to the left says the third, and so on, continuing leftward around the circle (a child may be reached more than once when is larger than the number of children still standing). The child who says the -th (last) syllable is counted out and leaves the circle.
- The first round is begun by child .
- Every later round is begun by the child immediately to the left of the child who was just counted out.
The counting is repeated, round after round, until no child remains.

We watch a whole game and record the order in which the children left the circle. From this order alone we want to recover how many syllables the rhyme had. Given the leaving order, write a program that finds the smallest positive integer for which a -syllable rhyme makes the children leave in exactly that order, or reports that no such exists.
Input
The first line contains one integer (). The second line contains integers separated by single spaces; the -th of them is the round in which child left the circle. These numbers form a permutation of to .
Output
Print, on a single line, the smallest number of syllables the rhyme can have. If no such exists, print the word NIE instead.