跳到正文

题解

题解:P7818 [RC-05] 排列

shinzAnmono约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月2日
篇幅
约 5 分钟
获赞
5
题目
P7818

版本

  1. v1当前

English version of this editorial is provided after the sample code.

考虑字典序最小的套路是贪心,首先要知道从位置 aa 到 bb 需要 ∣a−b∣|a-b| 次操作。我们在当前可操作的队列中找到最小的进行操作即可。

使用线段树,树状数组维护即可。

坑点在于恰好 kk 次,若已经升序排序后次数有剩余则反复交换最后两个位置即可。

示例代码 / Sample Code:

C++
#include<iostream>
#include<algorithm>
const int sz=5e5+10;
const int inf=0x3fffffff;
int a[sz],b[sz],ans[sz],n;
struct BIT{
    int sum[sz];
    void add(int p,int val){
        for(int i=p;i<=n;i+=i&-i)sum[i]+=val;
    }
    int query(int p){
        int res=0;
        for(int i=p;i>=1;i-=i&-i)res+=sum[i];
        return res;
    }
}bit;
struct SegT{
    int tree[sz<<2];
    void build(int p,int ln,int rn){
        if(ln==rn)return tree[p]=a[ln],void();
        int mid=ln+rn>>1;
        build(p<<1,ln,mid);
        build(p<<1|1,mid+1,rn);
        tree[p]=std::min(tree[p<<1],tree[p<<1|1]);
    }
    void change(int p,int ln,int rn,int pos,int val){
        if(ln==rn)return tree[p]=val,void();
        int mid=ln+rn>>1;
        if(pos<=mid)change(p<<1,ln,mid,pos,val);
        else change(p<<1|1,mid+1,rn,pos,val);
        tree[p]=std::min(tree[p<<1],tree[p<<1|1]);
    }
    int query(int p,int ln,int rn,int l,int r){
        if(ln>=l&&rn<=r)return tree[p];
        int mid=ln+rn>>1,res=inf;
        if(l<=mid)res=std::min(res,query(p<<1,ln,mid,l,r));
        if(r>mid)res=std::min(res,query(p<<1|1,mid+1,rn,l,r));
        return res;
    }
}st;
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    long long k;
    std::cin>>n>>k;
    for(int i=1;i<=n;i++)std::cin>>a[i],b[a[i]]=i;
    st.build(1,1,n);
    for(int i=1;i<=n;i++){
        int l=1,r=n;
        while(l<r){
            int mid=l+r>>1;
            if(mid-bit.query(mid)>k)r=mid;
            else l=mid+1;
        }
        int val=st.query(1,1,n,1,l),pos=b[val],t=pos-bit.query(pos)-1;
        ans[i]=val,k-=t,bit.add(pos,1),st.change(1,1,n,pos,inf);
    }
    if(k&1)std::swap(ans[n-1],ans[n]);
    for(int i=1;i<=n;i++)std::cout<<ans[i]<<" ";
    std::cout<<"\n";
    return 0;
}

English Version

The trick to consider the minimum lexicographic order problem is greedy. First, we know that ∣a−b∣|a-b| operations are required from position aa to bb. We just need to find the smallest one in the current operable value queue and perform the operation.

We can use Binary Indexed Tree(Fenwick Tree) and Segment Tree.

Moreover, the number of operations is exactly kk. So after the array is sorted, we repeatedly operate on the last two values.

原文