One day, Twilight Sparkle are interested in what to sort a sequence of integers a1,? A2,?...,? An in non-decreasing order. Being A young unicorn, the only operation she can perform is a unit shift. That's, she can move the last element of the sequence to its beginning:
a
1,? a 2,?...,? a n? →? a n,? a 1,? a 2,?...,? a n?-? 1.
Help Twilight Sparkle to Calculate:what are the minimum number of operations that she needs to sort the sequence?
Input
The first line contains an integer n (2?≤? N? ≤?105). The second line containsn integer numbers a1,? A2,?...,? An(1?≤? ) Ai? ≤?105).
Output
If it ' s impossible to sort the sequence output -1. Otherwise output The minimum number of operations Twilight Sparkle needs to sort it.
Sample Test (s) Input
2
2 1
Output
1
Input
3
1 3 2
Output
-1
Input
2
1 2
Output
0
Idea: Just start thinking is wrong, only consider the adjacent three digits-! , you can try it out wrong when you try the data.
See how many a[i-1]>a[i], use S to write down, and then use now to write down the current number of subscript. To move (shift) The number is n-now-1, and then look at the value of S, if s==1, indicates that there may be movement to become
# include < iostream >
# include < cstrings >
# include < cstdio >
# include < string >
# include < cmath >
# include < algorithm >
# define LL int
# define 0 x3f3f3f3f inf
Using namespace STD.
Int a, [1000001].
Int main ()
{
Int n, m, I, j; Int k, x, y;
While (~ the scanf (" % d ", & n))
{
For (I = 0; I < n. I++)
{
The scanf (" % d ", & a [I]);
}
Int s = 0, now = 0; // form an initialization habit
For (I = 0; I < n - 1; I++)
{
If (a > [I] a [I + 1))
{
Now = I; < span id = "transmark" > < / span >
S++;
}
}
If (s = = 0)
{
Printf (" 0 \ n ");
The continue;
}
Else if (s = = 1 [0] && a > = a/n - 1)
{
Printf (" % d \ n, n - now - 1);
}
The else
{
Printf (" \ n - 1 ");
}
}
Return 0;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Codeforces Round #259 (Div. 2) b. Little Pony and Sort by Shift