题解:AT_arc209_d [ARC209D] A_A_i
闲话
帅炸了。
这是主播被
题意
给定长度为
题解
首先特判掉一些 corner case。
若
若
接下来考虑
首先和前面一种 case 类似,若存在
然后考虑所有
但是可以发现,这样没有考虑到那些
依照上述讨论实现即可。时间复杂度为
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x) & -(x))
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
const int N = 5e5 + 5;
template<typename T> inline void chk_min(T &x, T y) { x = min(x, y); }
template<typename T> inline void chk_max(T &x, T y) { x = max(x, y); }
int T, n, cnt, a[N];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> T;
while (T--) {
cin >> n, cnt = 0;
for (int i = 1; i <= n; ++i) cin >> a[i], cnt += a[i] == -1;
if (cnt == 1) {
int pos = 0, mnp = 0; bool flag = 0;
for (int i = n; i; --i) {
if (a[i] == -1) pos = i;
else {
if (a[i] == pos) { flag = 1; break; }
if (!mnp || a[i] <= a[mnp]) mnp = i;
}
}
if (!mnp) mnp = pos;
if (pos < a[mnp] || (pos == a[mnp] && pos < mnp)) mnp = pos;
a[pos] = flag ? 1 : mnp;
} else if (a[1] == -1 || a[1] == 1) {
for (int i = 1; i <= n; ++i) if (a[i] == -1) a[i] = 1;
} else if (cnt) {
for (int i = 1; i <= n; ++i) if (a[i] > i && a[a[i]] == -1) a[a[i]] = 1;
int pos = 1;
for (int i = 1; i <= n; ++i)
if (a[i] == 1) { pos = i; break; }
else if (a[i] == -1) pos = i;
for (int i = 1; i <= n; ++i) if (~a[i] && a[i] < i && a[a[i]] == -1) {
int p = i + 1;
while (p <= n && ~a[p]) ++p;
chk_min(pos, p); break;
}
for (int i = 1; i <= n; ++i) if (a[i] == -1) a[i] = pos;
a[pos] = 1;
}
for (int i = 1; i <= n; ++i) cout << a[a[i]] << " \n"[i == n];
}
return 0;
}
:::