题解:P16919 [JLCPC 2026] 古明地恋世界第一

· · 题解

666,又不会了是吧?

题目大意

给定长度为 2n 的非降序列 c,它是序列 a 和其前缀最大值序列 b 混合排序的结果。请还原任意一个合法的 a,或判断无解。

解题思路

核心性质

首先具有两个重要的性质。

  1. 设数值 x 在 c 中出现 cnt_x 次。若 x 在前缀最大值序列 b 中出现 t_x 次,则 a 中至少有 1 个 x,因此 t_x\le cnt_x−1。
  2. 前 s 个位置的 a 和 b 共 2s 个元素都不超过第 s 个前缀最大值,因此所有不超过该值的数的总个数必须大于等于 2s。

    贪心判定

    从小到大枚举每个数值 x,维护当前能构造的最长前缀长度 s,设总出现次数为 sum,则执行 sum\leftarrow sum+cnt_x,更新 s=\min(\lfloor 2sum\rfloor, s+cnt_x−1)。遍历结束后,若 s=n 则有解,否则无解。

    构造方案

    按前缀最大值分段,每段对应一个数值 v,段长为该值贡献的 t_v。每段第一个位置放置 v(作为新的前缀最大值),剩余位置优先填充最小的可用数,以保证前缀最大值不变。

Code 代码

#include<bits/stdc++.h>
#define re register
#define il inline __attribute__((always_inline))
using namespace std;
const int MAXN=3e5+10;
const int READ=1<<20;

unsigned char buf[READ],*p1=buf,*p2=buf;
il int gc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,READ,stdin),p1==p2)?EOF:*p1++;}
il void read(int &x){
    re int ch=gc();x=0;
    while(ch<'0'||ch>'9')ch=gc();
    while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=gc();
}
il void write(int x){
    if(x>9)write(x/10);
    putchar(x%10+'0');
}

int cnt[MAXN];

int main(){
    int T;read(T);
    while(T--){
        int n;read(n);
        vector<int> used;
        for(re int i=0;i<(n<<1);i++){
            int x;read(x);
            if(!cnt[x]) used.push_back(x);
            cnt[x]++;
        }

        vector<int> v,le;
        int sum=0,s=0;
        for(re int x=1;x<=n;x++){
            if(!cnt[x]) continue;
            sum+=cnt[x];
            int ns=min(sum>>1,s+cnt[x]-1);
            if(ns>s){
                v.push_back(x);
                le.push_back(ns-s);
                s=ns;
            }
        }

        if(s!=n){
            puts("No");
            for(int x:used) cnt[x]=0;
            continue;
        }

        for(re int i=0;i<v.size();i++)
            cnt[v[i]]-=le[i];

        vector<int> ans;
        ans.reserve(n);
        int p=1;
        for(re int i=0;i<v.size();i++){
            int val=v[i],len=le[i];
            ans.push_back(val);
            cnt[val]--;
            while(--len){
                while(p<=n&&!cnt[p]) p++;
                ans.push_back(p);
                cnt[p]--;
            }
        }

        puts("Yes");
        for(re int i=0;i<n;i++){
            if(i) putchar(' ');
            write(ans[i]);
        }
        putchar('\n');

        for(int x:used) cnt[x]=0;
    }
    return 0;
}

886,希望提交记录里能够多几条AC记录。