首先如果 使 显然不劣,随后如果 使每个 都 即可。于是下文保证 。
如果存在 使得 ,我们要优先保证 更小,于是 。如果 中只剩一个 ,由于所有 都满足 ,于是我们优先满足 尽量小,再满足 尽量小,使 ,随后使 取 中最靠前的最小值位置即可。
如果存在两个或更多 :
- 不存在 。
- 存在 。设 是满足条件的最小值,使所有 即可。
- 不存在 。设 是最大的满足 的位置,要求 ,随后使 的 即可。
- 存在 。设 是满足条件的 的最小值。
- 存在 或 。设 是满足条件的最小值,使 ,随后 的 即可。
- 否则按照不存在 且不存在 做。
模拟即可,时间复杂度 。
Code:
#include<bits/stdc++.h>
#define mem(a, v) memset(a, v, sizeof(a))
using namespace std;
const int maxn = 5e5 + 10;
int t, n;
int a[maxn];
inline void calc(){
int pos1 = 0, pos2 = 0;
for (int i = 1; i <= n; i++){
a[i] == 1 && (pos1 = i), !~a[i] && (pos2 = i);
}
if (pos1){
for (int i = 1; i <= n; i++){
!~a[i] && (a[i] = pos1);
}
}else{
pos2 && (a[pos2] = 1);
for (int i = 1; i <= n; i++){
!~a[i] && (a[i] = pos2);
}
}
}
int main(){
scanf("%d", &t);
while (t--){
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
if (!~a[1]){
a[1] = 1;
}
if (a[1] == 1){
for (int i = 1; i <= n; i++){
!~a[i] && (a[i] = 1);
}
}else{
for (int i = 1; i <= n; i++){
if (a[i] > i && !~a[a[i]]){
a[a[i]] = 1;
}
}
int mn = 0, cnt = 0;
for (int i = 1; i <= n; i++){
!mn && !~a[a[i]] && (mn = i), cnt += !~a[i];
}
if (cnt == 1){
int pos = 0;
for (int i = 1; i <= n; i++){
!~a[i] && (pos = i);
}
pair<int, int> val = make_pair(pos, pos);
for (int i = 1; i <= n; i++){
i != pos && (val = min(val, make_pair(a[i], i)), 1538);
}
a[pos] = val.second;
}else{
if (mn){
int pos = 0;
for (int i = 1; i <= n; i++){
if (i > mn && !~a[i] || a[i] == 1){
pos = i;
break;
}
}
if (pos){
a[pos] = 1;
for (int i = 1; i <= n; i++){
!~a[i] && (a[i] = pos);
}
}else{
calc();
}
}else{
calc();
}
}
}
for (int i = 1; i <= n; i++){
printf("%d ", a[a[i]]);
}
putchar('\n');
}
return 0;
}