跳到正文

题解

[Solution]「ABC455-D」Card Pile Query

MindOnFeet_约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年4月28日
更新
2026年4月28日
篇幅
约 4 分钟

版本

  1. v1当前

我赛时大约 40 分钟完成了 ABCEF,可是太弱,接近 80 分钟时才通过了此题,大佬们几分钟就过了,用的链表和并查集我都想不到。并且一度认为这题比 E 和 F 要难。

本题需要维护一个动态的堆叠结构,每次操作需要把 CiC_i 上方的所有卡片移动到 PiP_i 的顶部。注意到这正是一个“分裂”再“合并”的过程,所以可以使用 FHQ-Treap 来维护。平衡树的模板本文不再赘述,具体来讲讲每次操作怎么处理。

对于每次操作 (Ci,Pi)(C_i,P_i),我们需要:

  1. 找到 CiC_i 所在的堆的根 rcrc 和 PiP_i 所在的根 rprp。
  2. 获取 CiC_i 在目前堆的排名 pospos。
  3. 将 CiC_i 所在的堆分裂为前 pospos 张(移走的)和留下的。
  4. 更新原堆。
  5. 把移走的和目标堆合并并更新。

这样能做到 O(n+Qlog⁡n)O(n+Q\log n) 的复杂度,如果想做到更优请移步其它题解。

参考代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5;
int n,q,c,p,root[N],ls[N],rs[N],siz[N],fa[N],rnd[N],hid[N];
// FHQ-Treap 模板
void pushup(int x){
    siz[x]=siz[ls[x]]+siz[rs[x]]+1;
    if(ls[x]) fa[ls[x]]=x;
    if(rs[x]) fa[rs[x]]=x;
}
int merge(int x,int y){
    if(!x||!y) return x|y;
    if(rnd[x]<rnd[y]){
        rs[x]=merge(rs[x],y);
        pushup(x);
        return x;
    }else{
        ls[y]=merge(x,ls[y]);
        pushup(y);
        return y;
    }
}
void split(int rt,int k,int &x,int &y){
    if(!rt){x=y=0;return;}
    if(siz[ls[rt]]<k){
        x=rt;
        split(rs[rt],k-siz[ls[rt]]-1,rs[x],y);
        pushup(x);
    }else{
        y=rt;
        split(ls[rt],k,x,ls[y]);
        pushup(y);
    }
}
int get_rank(int x){
    int res=siz[ls[x]]+1;
    while(fa[x]){
        if(rs[fa[x]]==x) res+=siz[ls[fa[x]]]+1;
        x=fa[x];
    }
    return res;
}
int get_root(int x){
    while(fa[x]) x=fa[x];
    return x;
}
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++) root[i]=i,siz[i]=1,hid[i]=i,rnd[i]=rand();
    while(q--){
        cin>>c>>p;
        int rc=get_root(c),rp=get_root(p);
        if(rc==rp) continue;
        int heap_c=hid[rc],heap_p=hid[rp],pos=get_rank(c),L,R;
        split(rc,pos,L,R);
        if(R) root[heap_c]=R,fa[R]=0,hid[R]=heap_c;
        else root[heap_c]=0;
        int new_rp=merge(L,rp);
        root[heap_p]=new_rp;
        if(new_rp) fa[new_rp]=0,hid[new_rp]=heap_p;
    }
    for(int i=1;i<=n;i++) cout<<siz[root[i]]<<' ';
    return 0;
}
原文