Link: http://codeforces.com/contest/454/problem/ B
B. Little Pony and sort by shifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output
One day, Twilight Sparkle is interested in how to sort a sequence of IntegersA1 ,?A2 ,?...,?ANIn non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
A1 ,?
A2 ,?...,?
A
N? →?
A
N,?
A1 ,?
A2 ,?...,?
A
N? -? 1.
Help Twilight Sparkle to calculate: What is the minimum number of operations that she needs to sort the sequence?
Input
The first line contains an integerN(2? ≤?N? ≤? (105). The second line containsNInteger numbersA1 ,?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
22 1
Output
1
Input
31 3 2
Output
-1
Input
21 2
Output
0
Ideas:
Judge whether there are several "downhill", that is, the number behind is smaller than the previous one;
If no value exists, 0 is output. If more than one value exists,-1 is output. If there is one, the relationship between a [1] and a [n] needs to be determined;
The Code is as follows:
#include <cstdio>#include <cstring>int main(){int n;int i, j;int a[100017];while(~scanf("%d",&n)){for(i = 1; i <= n; i++){scanf("%d",&a[i]);}int cont = 0;int t;for(i = 2; i <= n; i++){if(a[i] < a[i-1]){cont++;t = i;}}if(cont == 0)printf("0\n");else if(cont > 1)printf("-1\n");else if(cont == 1 && a[n] <= a[1])printf("%d\n",n-t+1);elseprintf("-1\n");}return 0;}