题解:AT_arc209_d [ARC209D] A_A_i

· · 题解

场上把时间都花在 C 题上了,其实 D 比 C 简单,就是一个贪心。

首先 a_1 未确定是平凡的,把所有未确定的数都填为 1 一定最优。a_1=1 同理。

贪心,从前往后依次考虑每一位。我们称 a_i 为 i 指向的位置。分类讨论:

  1. 第 i 位还未确定:我们希望第 i 位指向的位置填 1,但还不急着确定它,可以延迟考虑。

  2. 第 i 位已确定,指向一个确定的位置:跳过即可。

  3. 第 i 位已确定,指向后面一个未确定的位置:把 a_i 填上 1,并将 a_i 标记为已确定。

  4. 第 i 位已确定,指向前面一个未确定的位置:现在我们希望前面所有未确定的位置全指向一个位置 a_i,且 a_i 填了 1。有两种选择:第一个已经确定的 1,或 i 后面第一个未确定的位置。取其中较小者即可。如果两种选择都没有,则 break,最后统一处理。

最后如果还有未确定的数,先看有没有确定的 1,如果有则都指向第一个确定的 1。否则:

  1. 未确定的数 >1 个:让最后一个未确定的数填 1,其余数均指向它。
  2. 未确定的数恰有一个:要先最小化它指向的位置的值,再最小化它指向的位置。注意还能指向自己。
#include<bits/stdc++.h>
#define N 500005
using namespace std;
template<typename T> void read(T &x){
    x=0;int f=0;char c=getchar();
    for(;c<'0'||c>'9';c=getchar()) f=(c=='-');
    for(;c>='0'&&c<='9';c=getchar()) x=x*10+c-'0';
    if(f) x=-x;
}
int n;
int a[N];
int st[N],top;
int main(){
    int T;
    read(T);
    while(T--){
        read(n);
        for(int i=1;i<=n;i++) read(a[i]);
        if(a[1]==-1||a[1]==1){
            for(int i=1;i<=n;i++) if(a[i]==-1) a[i]=1;
            for(int i=1;i<=n;i++) cout<<a[a[i]]<<" ";
            cout<<"\n";
            continue;
        }
        int pos=1,pos2=1;
        while(pos<=n&&a[pos]!=1) pos++;
        top=0;
        for(int i=1;i<=n;i++){
            if(a[i]==-1) {
                st[++top]=i;
                continue;
            }
            if(a[a[i]]!=-1) continue;
            if(a[i]>i){
                a[a[i]]=1;
                pos=min(pos,a[i]);
            }else{
                pos2=max(pos2,i);
                while(pos2<=n&&a[pos2]!=-1) pos2++;
                if(pos==n+1&&pos2==n+1) break;
                if(pos<pos2){
                    while(top) a[st[top--]]=pos;
                }else{
                    while(top) a[st[top--]]=pos2;
                    a[pos2]=1;
                    pos=pos2;
                }
            }
        }
        if(pos==n+1&&top){
            if(top==1){
                int x=st[top--],mn=0;
                for(int i=1;i<=n;i++){
                    if(i==x) continue;
                    if(!mn||a[i]<a[mn]) mn=i;
                }
                if(x<a[mn]||x==a[mn]&&x<mn) mn=x;
                a[x]=mn;
            }else{
                pos=st[top--];
                a[pos]=1;   
            }
        }
        while(top) a[st[top--]]=pos;
        for(int i=1;i<=n;i++) cout<<a[a[i]]<<" ";
        cout<<"\n";
    }
    return 0;
}