One day, Twilight Sparkle is interested in how 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 is, she can move the last element of the sequence to its beginning:
Help Twiligh t Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
InputThe first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
OutputIf 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) Input2 2 1Output
1Input
3 1 3 2Output
-1Input
2 1 2Output
0
思路:剛開始思路就錯了,只考慮相鄰的三位數- -!,試數據的時候可以試出來錯。
看有多少個a[i-1]>a[i],用S記下,然後用now分別記下當前數的下標。要移動(shift)的數就是n-now-1,然後看S的值,如果S==1,表示可能會有移動成為
#include#include #include #include #include #include #define LL int #define inf 0x3f3f3f3f using namespace std; int a[1000001]; int main() { int n,m,i,j;int k,x,y; while(~scanf(%d,&n)) { for(i=0;i a[i+1]) { now=i; s++; } } if(s==0) { printf(0 ); continue; } else if(s==1&&a[0]>=a[n-1]) { printf(%d ,n-now-1); } else { printf(-1 ); } } return 0; }