【Bitwise Xor】解题报告

· · 个人记录

题面

题意

令一个合法的数列 b 满足:对于任意数对 (i,j) ,满足 b_i \oplus b_j \geq x。

输入一个长度为 n 的数列 a ,和 x 。求数列 a 中有多少个子序列合法。

1 \leq n \leq 0,0 \leq a_i,x \leq 2^{60}-1

题解

首先知道:对于一个排好序的数列 b ,当 b_i \oplus b_j 最小时, b_i,b_j 一定相邻。

证明略。其实是懒得写。

所以先将 a_i 排好序,进行dp:

设 f_i 表示以 a_i 结尾的子序列中合法的子序列数量。则有转移:

f_i=1+\sum_{j=1 \bigwedge a_i \oplus a_j \geq x}^{i-1} f_j

根据样例数据可知,只有一个元素的子序列也合法,所以要加上 a_i 单独组成一个子序列的情况。

然而这么转移是 $O(n^2)$ 的,考虑使用 01trie 优化这dp的转移。 在dp过程中将 $a_i$ 依次插入01trie,01trie上的每个结点记录一个数组 $sum_u$ ,存储其子树中已计算出的 $f_i$ 的总和。 设当前转移到 $i$ ,当前位置的数为 $a_i$,在01trie上统计答案,即求 $\sum_{j=1 \bigwedge a_i \oplus a_j \geq x}^{i-1} f_j$: 1. 从根节点 $u$ 开始。 2. 若 $x$ 在第 $k$ 位上是 $1$ ( $k$ 表示当前比较的是第几位,即与叶节点的距离),则`u=ch[u][((a[i]>>k)&1)==0]`。 3. 否则`ans+=sum[ch[u][((a[i]>>k)&1)==0]],u=ch[u][((a[i]>>k)&1)!=0]`。当 $x$ 的某一位位 $1$ 时,$a_j$ 的这一位如果与 $a_i$ 相反,则 $a_i \oplus a_j > x$ 。 4. 当 $u=0$ 时,显然无法再向下走,则退出循环。 5. 最后 `ans+=sum[u]` ,使得 $a_i \oplus a_j = x$ 的情况得以计入答案,因为最后走下来如果 $u \neq 0$ 则 $u$ 这个结点表示的数为 $a_j=x \oplus a_i$,即 $a_i \oplus a_j = x$。 --- ${\rm{Code}}$: ```cpp #include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #define maxn 300005 #define R register #define INF 0x3f3f3f3f #define mod 998244353 #define lxl long long using namespace std; inline lxl read() { lxl x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();} while(ch>='0'&&ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} return x*f; } lxl n,x,a[maxn]; int ch[maxn*60][2],tot=1; lxl sum[maxn*60],f[maxn]; inline void insert(lxl s,lxl v) { int u=1; for(R lxl i=60;i>=0;--i) { int c=((s>>i)&1); if(!ch[u][c]) ch[u][c]=++tot; u=ch[u][c]; sum[u]=(sum[u]+v)%mod; } } inline lxl query(lxl s) { lxl ans=0;int u=1; for(R int i=60;i>=0;--i) { if((x>>i)&1) u=ch[u][((s>>i)&1)==0]; else { ans=(ans+sum[ch[u][((s>>i)&1)==0]])%mod; u=ch[u][((s>>i)&1)!=0]; } } return (ans+sum[u])%mod; } int main() { //freopen("CFGYM102337B.in","r",stdin); n=read(),x=read(); for(R int i=1;i<=n;++i) a[i]=read(); sort(a+1,a+n+1); for(R int i=1;i<=n;++i) { f[i]=(query(a[i])+1)%mod; insert(a[i],f[i]); } lxl ans=0; for(R int i=1;i<=n;++i) ans=(ans+f[i])%mod; printf("%lld\n",ans); return 0; } ```