PQ-tree 题解:P7341 『MdOI R4』Phoenix

· · 题解

等式取到了下界因为按位考虑每位为点减边。因此等价于要求每bit出现为连续段。

若有解,则可以作如下推断:将所有要求看作连续段的要求,所以所有要求都可以浓缩成pq tree。

即推导要求,转化限制,分析答案的形态。

推导到最后,就变成独立无限制的排列 或者 可以reverse的链,构成的嵌套树,也就是pq树

pq树看似有点难写,oi-wiki叽里咕噜写了很多行。但是经过简化,其实非常短的


#include<bits/stdc++.h>
#define i64 int64_t
#define vec basic_string<int>
using namespace std;

const int maxn=1e5+10,mod=998244353;

struct{
    int typ;vec S;int col;
    void mk(int c,vec T){typ=c;S={};for(int v:T)if(v)S+=v;}
}t[maxn*3];int tot,rt;

int n,m;i64 A[maxn];

void mkcol(int u){
    if(u<=n)return;
    int M=0;for(int v:t[u].S)mkcol(v),M|=1<<t[v].col;
    t[u].col=M==1<<2?2:M==1<<0?0:1;
}
int mk(int typ,vec S){
    int i=0;for(int v:S)if(v)S[i++]=v;
    S.resize(i);
    if(i<=1)return S[0];
    t[++tot].mk(typ,S);return tot;
}
void sepsQ(int u){
    if(t[u].typ==0){
        vec L,R;int U=0;
        for(int v:t[u].S){
            if(t[v].col==0)R+=v;
            if(t[v].col==1)sepsQ(v),U=v;
            if(t[v].col==2)L+=v;
        }
        return t[u].mk(1,mk(0,L)+t[U].S+mk(0,R));
    }else{
        vec U;
        for(int v:t[u].S)
            if(t[v].col==1)sepsQ(v),U+=t[v].S;
            else U+=v;
        return t[u].mk(1,U);
    }
}
void seps(int u){
    int p0=0,p1=0,c2=0;
    for(int v:t[u].S)if(t[v].col==1)(p0?p1:p0)=v;else c2+=t[v].col==2;
    if(!p1&&!c2)return seps(p0);

    if(t[u].typ==0){
        vec H,R;
        for(int v:t[u].S)if(t[v].col==2)H+=v;else if(t[v].col==0)R+=v;
        H={mk(0,H)};
        if(p0)sepsQ(p0),H+=t[p0].S;
        if(p1)sepsQ(p1),
            reverse(t[p1].S.begin(),t[p1].S.end()),H=t[p1].S+H;
        if(R.empty())return t[u].mk(1,H);
        t[u].mk(0,mk(1,H)+R);
    }else return sepsQ(u);
}

i64 ans;
i64 fac(int n){return n?fac(n-1)*n%mod:1;}
void calc(int u){
    if(t[u].typ==0)(ans*=fac(t[u].S.size()))%=mod;
    else(ans*=2)%=mod;
    for(int v:t[u].S)calc(v);
}

void sol(){
    for(int i=1;i<=tot;++i)t[i]={};
    cin>>n>>m;
    tot=n;vec H;for(int i=1;i<=n;++i)H+=i;
    rt=mk(0,H);
    for(int i=1;i<=n;++i)cin>>A[i];
    for(int j=0;j<m;++j){
        for(int i=1;i<=n;++i)t[i].col=A[i]>>j&1?2:0;
        mkcol(rt);if(t[rt].col==1)seps(rt);
    }
    ans=1;calc(rt);cout<<ans<<'\n';
}

signed main(){
    ios::sync_with_stdio(0),cin.tie(0);
    int T;cin>>T;while(T--)sol();
}

这种代码写错的地方无非就是新建节点,此写法只有三处用到了新建节点,可想而知和虚树难度差不多,所以书写难度已经足够简单了。

这里的写法就是从顶向下更新,分裂的时候,讨论是否是P点,Q点的分裂是平凡的,P点如果就在此处裂开,那么递归到的子问题是强制建立的是Q点的,然后sepsQ就做了这个建立过程,是非常简单的。