定义一种名为星宿归位的操作:将数列中最后一个元素移动至数组中的第一位,并将原来的第一位及后面的数字依次后移。
大自然中有许多数列可以只通过星宿归位使其变成递增(非严格)的数列。
那么问题来了,给定一个数列,请你辅助山舞泣判断,是否可以只通过星宿归位将其变为递增(非严格)数列。如果可以请计算最少需要多少次星宿归位。
Input
多组输入数据。
每组数据第一行为一个整数n(1<=n<=100000),表示数列中数字的个数,第二行为n个数字。
Output
对每组输入数据,输出一行,包含一个整数,表示至少需要多少次操作才能获得递增(非严格)的数列
Sample Input
2
2 1
3
1 3 2
2
1 2
1
8
Sample Output
1
-1
0
0
#include<iostream>
using namespace std;
bool judge(int n, int a[])
{
for (int i = 0; i < n - 1; i++)
{
if (a[i] != a[i + 1])return false;
}
return true;
}
int main()
{
int n;
while (cin >> n)
{
int *a = new int[2 * n];
for (int i = 0; i < n; i++)//构建数组
{
cin >> a[i];
a[n + i] = a[i];
}
int position = 0;//初始化各个变量
int length = 1;
int MAXLEN = 1;
int MAXPOS = 0;
for (int i = 0; i < 2 * n - 1; i++)//寻找最大连续上升序列
{
if (a[i] <= a[i + 1])
{
length++;
position = i + 1;
}
if (a[i] > a[i + 1]) length = 1;//复位
if (MAXLEN <= length)//更新最大值
{
MAXLEN = length;
MAXPOS = position;
}
}
if (n == 1 || judge(n, a)) {
cout << 0 << endl;
}
else if (MAXLEN == n)
cout << 2 * n - MAXPOS - 1 << endl;
else cout << -1 << endl;
}
return 0;
}