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;
    }

 

转载于:https://www.cnblogs.com/nextroad/p/3915562.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值