Little Pony and Sort by Shift

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:

a1, a2, ..., an → an, a1, a2, ..., an - 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 integer n (2 ≤ n ≤ 105). The second line contains n 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.

题目大意是说一个序列只能把底部元素放到首部。目标是把该序列调整成不下降序列。经过题目给的样例和手测数据基本可以确定一个可调整的序列满足A[1]~A[i]不下降,A[i+1]~A[n]不下降且A[n]<=A[1(这一点需要自己去体会为什么)。于是根据这个策略可以写出如下程序(程序写的有一些复杂,将就下吧,毕竟LZ才从pascal转C++....)

#include<iostream>
using namespace std;
long a[100002];
int main(){
    long n=0;
    cin >> n;
    for (long i=0;i<=n-1;++i) cin >> a[i];
    long i=0,j=0;
    while (a[i]<=a[i+1]) ++i;
    if (i==n-1)   {cout <<0; return 0;}
    ++i; ++j;
    while (a[i]<=a[i+1]) {++i; ++j;}
    if (i!=n-1) { cout <<-1;  return 0; }
        else if (a[n-1]>a[0]) {cout <<-1; return 0;}
            else cout <<j;
    return 0;
    }

 

posted @ 2014-08-15 19:38  S_Black  阅读(281)  评论(0编辑  收藏  举报