CF1720D2 题解

· · 题解

前言

01Trie 优化 dp 好题,这是我第一道模板性不那么强的 01Trie 题(

注明:下文的 \oplus 符号均代表异或(\operatorname{xor},^)运算。

思路

如果 a_i \oplus j<a_j \oplus i,那么说明,a_i \oplus j 和 a_j \oplus i 一定有前面 k 位都是相同的,第 k+1 位的时候,前者是 0 而后者是 1。

但是这样维护的话,是包含两个参数 i,j 的,我们尝试把它变成只有一个参数进行维护。

对于前面 k 位,我们假设 a_i (后面都指在二进制下)第 k 位是 A,j 第 k 位是 B,a_j 第 k 位是 C,i 第 k 位是 D。

那么有:A \oplus B = C \oplus D。

我们进行移项得到,A \oplus D=B\oplus C,即 a_i \oplus i 的第 k 位 =a_j \oplus j 的第 k 位。于是前 k 位我们转化成了一个参数的问题。

而第 k+1 位怎么解决呢?我们现在可以得到,A \oplus B=0,C \oplus D=1。也就是说,A=B=C,D 中任意一个。

考虑进行分类讨论:

  1. 若 A=B=C,则 A \oplus D=1,B \oplus C=0。

  2. 若 A=B=D,则 A \oplus D=0,B \oplus C=1。

所以我们发现它们一定是在相反的那一方更新到的答案。至此,我们把它成功的转化成了只含有一个参数的问题。

剩下的就比较显然了。我们只需要找到所有的满足上述条件的 dp 的最大值即可。显然用 01Trie 即可维护。

查询最大值的时候,我们就从前往后一位一位找,每次用当前位取反的那一边更新答案。然后继续往下找,直到找不到了就停止。

然后我们把当前的值插入 Trie。对 a_i \oplus i 进行拆位,插入 01 \operatorname{Trie} 中,对每一个节点更新它的 \max。

最后输出即可。复杂度是 O(n \log w)。

代码

#include <bits/stdc++.h>
using namespace std;
const int MAXN=300005;
int tr[MAXN*31][2],mx[MAXN*31][2],tot=1; // 空间开 30 倍
int a[MAXN],dp[MAXN];
void insert(int x,int val){
    int now=1,p=a[x]^(x-1); // 这里要减一,因为题目中下标从零开始,我一开始没看到调了好久。 
    for(int j=30;j>=0;j--){
//      cout<<"qwq "<<now<<endl;
        bool bitp=p&(1<<j),bitx=(x-1)&(1<<j); // 分别记录两个二进制位(要用 bool 存储!) 
//      cout<<bitp<<" "<<bitx<<endl;
        if(!tr[now][bitp]) tr[now][bitp]=++tot; // 如果没有,那么新建节点 
        mx[tr[now][bitp]][bitx]=max(mx[tr[now][bitp]][bitx],val); // 更新最大值 
        now=tr[now][bitp]; // 往后接着找 
    }
}
int query(int x){
    int now=1,p=a[x]^(x-1),ans=0; // 这里减一是同理的 
    for(int j=30;j>=0;j--){
//      cout<<"qwq "<<now<<endl;
        bool bitp=p&(1<<j),bitx=a[x]&(1<<j); // 这里要用 a[x],至于是为什么,留给读者思考(其实随便推一推就好了) 
//      cout<<bitp<<" "<<bitx<<endl;
        if(tr[now][!bitp]) ans=max(ans,mx[tr[now][!bitp]][!bitx]); // 如果另一边有数,说明有贡献 
        if(tr[now][bitp]) now=tr[now][bitp]; // 然后往下走 
        else break; // 如果没了就撤出 
    }
    return ans;
}
int main(){
    int T; cin>>T;
    while(T--){
        int n,maxn=-1e9; cin>>n;
        for(int i=1;i<=n;i++) cin>>a[i];
        for(int i=1;i<=n;i++){
            dp[i]=query(i)+1; // 每次在最大值的基础上加一 
//          cout<<"dp["<<i<<"]="<<dp[i]<<endl;
            insert(i,dp[i]); // 插入最大值 
            maxn=max(maxn,dp[i]); // 求 max 
        }
        cout<<maxn<<endl;
        for(int i=1;i<=tot;i++){ // 最后记得清空字典树! 
            tr[i][0]=tr[i][1]=0;
            mx[i][0]=mx[i][1]=0;
        }tot=1;
    }
    return 0;
}