码迷,mamicode.com
首页 > 其他好文 > 详细

Little Pony and Sort by Shift

时间:2014-08-15 20:55:49      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   strong   数据   for   ar   div   

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

 

Little Pony and Sort by Shift,布布扣,bubuko.com

Little Pony and Sort by Shift

标签:blog   os   io   strong   数据   for   ar   div   

原文地址:http://www.cnblogs.com/nextroad/p/3915562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!