War

Time limit2sMemory limit512 MB

Summary
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 nn worms and nn humans will fight.

Intelligence reports say that only the ii-th worm can be defeated by the ii-th human.

The general has lined up the humans, and he knows that the human in position ii will fight worm aia_i. Humanity wins the war only if every human wins their fight.

At first the general placed the ii-th human in position ii 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 nn, the number of fighters on each side. (1≤n≤2⋅1051 \le n \le 2 \cdot 10^5)

The second line contains nn distinct integers a1,a2,…,ana_1, a_2, \ldots, a_n, where aia_i is the number of the worm that fights the human in position ii of the line. (1≤ai≤n1 \le a_i \le n, and ai≠aja_i \ne a_j if i≠ji \ne j)

Output

Print the number kk, 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

Examples2

  1. Example 1

    Input
    6
    1 6 4 2 3 5
    
    Expected output
    3
    
  2. Example 2

    Input
    3
    1 3 2
    
    Expected output
    -1