War
Time limit2sMemory limit512 MB
Given a permutation of worm targets, reorder humans only by moving the last to the front and find the minimum moves for a winning formation, or report -1.
- Level
Medium7 of 10
- Topics
- Array, Sorting, Implementation
- Solved
- No attempts yet
Problem
Humanity is about to fight its final battle against giant worms from outer space. Exactly worms and humans will fight.
Intelligence reports say that only the -th worm can be defeated by the -th human.
The general has lined up the humans, and he knows that the human in position will fight worm . Humanity wins the war only if every human wins their fight.
At first the general placed the -th human in position of the line. The battle is approaching, so the general must change the order of the line. He can only take the person at the back of the line and bring them to the front, and each such operation takes 1 second. After this operation, every other person's position increases by one.
Write a program to compute the minimum number of seconds the general needs to put the humans into a formation where they win the war.
Input
The first line contains the integer , the number of fighters on each side. ()
The second line contains distinct integers , where is the number of the worm that fights the human in position of the line. (, and if )
Output
Print the number , the minimum number of seconds the general must spend so that the humans win. If winning against the worms is impossible, print "-1".
Hint
In the first example the fighters fight as follows:
Worms 1 6 4 2 3 5
Humans 1 2 3 4 5 6
Worm 1 wins the fight, so humanity cannot win the war. After the first move the fight looks like this:
Worms 1 6 4 2 3 5
Humans 6 1 2 3 4 5
Here worm 5 wins, so he must move again. After the second move it looks like this:
Worms 1 6 4 2 3 5
Humans 5 6 1 2 3 4
Here worms 2, 3, and 6 win. So he makes one more move, and humanity wins the war.
Worms 1 6 4 2 3 5
Humans 4 5 6 1 2 3