給定長度 n(≤ 105)的整數序列,允許操作:將最後一個元素移到最前面(右循環移位 1 位)。求最少操作次數使序列非遞減,不可能則輸出 −1。
序列經過 k 次操作後等價於原序列循環右移 k 位。
若存在排序後的非遞減序列,則原序列必須是某個非遞減序列的循環移位。
即原序列中「降序對」a[i] > a[i+1] 的個數至多為 1。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n;
while (cin >> n) {
vector<int> a(n);
for (int &x : a) cin >> x;
int cnt = 0, pos = -1;
for (int i = 0; i < n - 1; ++i)
if (a[i] > a[i + 1]) { ++cnt; pos = i; }
if (cnt == 0) cout << 0 << '\n';
else if (cnt == 1 && a[n - 1] <= a[0])
cout << n - pos - 1 << '\n';
else
cout << -1 << '\n';
}
return 0;
}
O(n) 時間,O(n) 空間。