CF1561E 题解
给定长度为奇数 的 到 的排列 ,要求找出一种长度不超过 的操作序列,使 $$a$$ 变为升序,或判断无解。操作如下:
- 选择一个 ,且 为奇数,将 到 翻转。
且为奇数,。
首先怎么判断无解,因为 是奇数,所以翻转操作不改变位置的奇偶性,所以有解的充要条件是 和 的奇偶性都相同。
考虑将两个数绑到一起且倒着操作,比如 和 一起操作,这样相当与每对数要在五次操作内移动到最后的位置。
我们假设现在考虑的数位置为 和 , 要移到位置 ,操作 表示前 的翻转操作,以下给出方案:
很不优的构造 /kk,时间复杂度 $$O(n^2)$$。
CODE
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 0; char c = 0;
while (!isdigit(c)) f |= c == '-', c = getchar();
while (isdigit(c)) x = (x << 3) + (x << 1) + (c & 15), c = getchar();
return f ? -x : x;
}
#define N 2040
int n, a[N];
vector<int> res;
int can(int n) {
for (int i = 1; i <= n; i ++) {
if ((i & 1) != (a[i] & 1)) return false;
}
return true;
}
int check(int x) {
for (int i = 1; i <= x; i ++) {
if (i != a[i]) return false;
}
return true;
}
void F(int x) {
res.emplace_back(x);
reverse(a + 1, a + x + 1);
}
signed main() {
for (int T = read(); T --;) {
res.clear();
n = read();
for (int i = 1; i <= n; i ++) a[i] = read();
if (!can(n)) { puts("-1"); continue; }
while (!check(n)) {
int x, y;
for (int i = 1; i <= n; i ++) {
if (a[i] == n) x = i;
if (a[i] == n - 1) y = i;
}
if (x == n && y == n - 1) { n -= 2; continue; }
if (x + 1 < y) F(x), F(y - 1), x = y - 1;
if (y + 1 < x) F(x), y = (x + 1 - y), F(y - 1), x = y - 1;
if (x + 1 == y) F(y + 1), x = (y + 2 - x), F(x);
else F(x);
F(n), n -= 2;
}
printf("%d\n", res.size());
for (auto x : res) printf("%d ", x);
if (res.size()) puts("");
}
return 0;
}CF1561E 题解
https://ybwa.github.io/p/9fedbdc6/