CF1720D2 题解
E1_de5truct0r · · 题解
前言
01Trie 优化 dp 好题,这是我第一道模板性不那么强的 01Trie 题(
注明:下文的 ^)运算。
思路
如果
但是这样维护的话,是包含两个参数
对于前面
那么有:
我们进行移项得到,
而第
考虑进行分类讨论:
-
若
A=B=C ,则A \oplus D=1,B \oplus C=0 。 -
若
A=B=D ,则A \oplus D=0,B \oplus C=1 。
所以我们发现它们一定是在相反的那一方更新到的答案。至此,我们把它成功的转化成了只含有一个参数的问题。
剩下的就比较显然了。我们只需要找到所有的满足上述条件的 dp 的最大值即可。显然用 01Trie 即可维护。
查询最大值的时候,我们就从前往后一位一位找,每次用当前位取反的那一边更新答案。然后继续往下找,直到找不到了就停止。
然后我们把当前的值插入 Trie。对
最后输出即可。复杂度是
代码
#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;
}