CF 454 B. Little Pony and Sort by Shift

来源:互联网 发布:mac移动硬盘重命名 编辑:程序博客网 时间:2024/06/06 10:59

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
22 1
output
1
input
31 3 2
output
-1
input
21 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;}


1 0
原创粉丝点击