题解:AT_arc209_d [ARC209D] A_A_i

· · 题解

首先如果 a_1 = -1 使 a_1 \gets 1 显然不劣,随后如果 a_1 = 1 使每个 a_i = -1 都 a_i \gets 1 即可。于是下文保证 a_1 > 1。

如果存在 i < j 使得 a_i = j, a_j = -1,我们要优先保证 b_i = a_{a_i} 更小,于是 a_j \gets 1。如果 \{a_i\} 中只剩一个 a_i = -1,由于所有 a_j = i 都满足 j > i,于是我们优先满足 a_{a_i} 尽量小,再满足 a_i 尽量小,使 a_i \gets i,随后使 a_i 取 \{a_i\} 中最靠前的最小值位置即可。

如果存在两个或更多 a_i = -1:

模拟即可,时间复杂度 \mathcal{O}(n)。

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;
}