题解:P14227 [ICPC 2024 Kunming I] 排列

· · 题解

感觉难度稍微有一点虚高。

考虑最朴素的做法,因为这是一个排列,所以可以暴力找每一个数所在的位置。二分的询问次数是 n\log n 的,很明显无法通过此题。

考虑稍微优化这个算法,发现前面已经确定过的位置就不需要继续确定了,这样做的询问次数是 \sum_{i=1}^{n} \lceil \log_2 n \rceil 的,在 n=1000 的情况下大概需要询问 8900 次左右,依旧无法通过此题。

这个逐个确定数的方法看起来没有什么前途,考虑换一种做法,如果我们同时考虑两个数,把一个数填前一半,另外一个数填后一半,这样我们非常高效的求出了在区间 [l,r] 内存在的数的集合 S,不断递归求解即可。这样的做法非常高效,可以在 6666 次询问内找到答案。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e3+5;
int n,a[N];
inline int print(int pos,int x,int y){
    cout<<"0 ";
    for(int i=1;i<=pos;++i){
        cout<<x<<" ";
    }
    for(int i=pos+1;i<=n;++i){
        cout<<y<<" ";
    }
    cout<<"\n";
    int w; cin>>w;
    return w;
}
inline void solve(int l,int r,vector<int> G){
    if (l==r){
        a[r]=G[0]; return;
    }
    random_shuffle(G.begin(),G.end());
    vector<int> temp[2];
    int pos=0,mid=(l+r)>>1;
    for(int i=0;i+1<G.size();++i){
        int w=print(mid,G[i],G[i+1]);
        if (w!=1){
            for(w=!w;pos<=i;++pos){
                temp[w].push_back(G[pos]);
            }
            temp[w^1].push_back(G[pos]);
            ++i; ++pos;
        }
    }
    if (pos!=G.size()){
        int w=0;
        if (temp[0].size()==mid-l+1) w=1;
        for(;pos<G.size();++pos){
            temp[w].push_back(G[pos]);
        }
    }
    solve(l,mid,temp[0]);
    solve(mid+1,r,temp[1]);
}
int main(){
    scanf("%d",&n);
    vector<int> G;
    for(int i=1;i<=n;++i){
        G.push_back(i);
    }
    solve(1,n,G);
    cout<<1<<" ";
    for(int i=1;i<=n;++i){
        cout<<a[i]<<" ";
    }
    cout<<"\n";
    return 0;
}