您的位置:首页 > 其它

CF 454 B. Little Pony and Sort by Shift

2014-08-02 19:21 465 查看
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.

Sample test(s)

input
2
2 1


output
1


input
3
1 3 2


output
-1


input
2
1 2


output
0

哎,无力吐槽,匿了。
策略:因为是升序,我们可以考虑首尾相连这样从最小值开始顺时针按升序排序符合就输出n-断点位子,否则输出-1;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<limits.h>
using namespace std;
const int maxn=1e5+10;
int a[maxn];

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int flag=0,pos;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            if(i&&a[i]<a[i-1])
            {
               flag++;
               pos=i;
            }
        }
        if(flag==0)
            cout<<0<<endl;
        else if(flag==1&&a[0]>=a[n-1])
            cout<<n-pos<<endl;
        else
            cout<<-1<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: