事实上,对于这种奇奇怪怪的位运算贡献,直接列式子一般很难写而且复杂度也不一定够好,但是如果尝试使用数位 dp 就很可能得到又好写复杂度又低的做法。
不妨从高到低确定 的每一位,考虑到第 位时思考我们要记录的信息:
-
只考虑已经填入的部分 是否与 完全相同。
-
已经填入的部分是否相同,或者说是否已经分叉。
-
如果还未分叉,那么我们只需要记录这个相同的前缀是什么,容易把所有 全部插入 trie 之后记录这个前缀对应的 trie 上点。
-
如果已经分叉,那么我们只需要记录贡献到 的那一项(显然会在分叉的那个二进制位上就知道是哪一项)已经被填入的前缀在 trie 上的对应点。
直接记忆化搜索,记录每个状态贡献到最终状态的方案数和贡献和即可。转移是简单的,时间复杂度 。
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod = 998244353;
const int maxn = 2e5+114;
int a[maxn];
int n,m;
int root,tot;
int ch[maxn*30][2];
int sz[maxn*30];
void Ins(int x){
int u=root;
for(int i=29;i>=0;i--){
sz[u]++;
if((1<<i)&x){
if(ch[u][1]==0) ch[u][1]=++tot;
u=ch[u][1];
}else{
if(ch[u][0]==0) ch[u][0]=++tot;
u=ch[u][0];
}
}
sz[u]++;
}
int f[maxn*30][2][2];
int dp[maxn*30][2][2];
int vis[maxn*30][2][2];
array<int,2> dfs(int h,int pos,bool flag,bool dif){
if(h==-1){
if(dif==true) return {sz[pos],0};
else return {sz[pos]*sz[pos]%mod,0};
}
if(vis[pos][flag][dif]==1) return {f[pos][flag][dif],dp[pos][flag][dif]};
vis[pos][flag][dif]=1;
array<int,2> res={0,0};
for(int c=0;c<2;c++){
if(flag==true&&c==1&&(!((1<<h)&m))) continue;
if(dif==false){
for(int C=0;C<2;C++){
if(ch[pos][C]!=0){
array<int,2> nxt=dfs(h-1,ch[pos][C],flag&(c==((m>>h)&1)),dif);
nxt[1]=(nxt[1]+nxt[0]*((c!=C)*(1<<h))%mod)%mod;
res[0]=(res[0]+nxt[0])%mod;
res[1]=(res[1]+nxt[1])%mod;
}
}
if(ch[pos][0]!=0&&ch[pos][1]!=0){
array<int,2> nxt=dfs(h-1,ch[pos][c],flag&(c==((m>>h)&1)),true);
nxt[0]=nxt[0]*sz[ch[pos][c^1]]%mod*2%mod;
nxt[1]=nxt[1]*sz[ch[pos][c^1]]%mod*2%mod;
res[0]=(res[0]+nxt[0])%mod;
res[1]=(res[1]+nxt[1])%mod;
}
}else{
for(int C=0;C<2;C++){
if(ch[pos][C]!=0){
array<int,2> nxt=dfs(h-1,ch[pos][C],flag&(c==((m>>h)&1)),dif);
nxt[1]=(nxt[1]+nxt[0]*((c!=C)*(1<<h))%mod)%mod;
res[0]=(res[0]+nxt[0])%mod;
res[1]=(res[1]+nxt[1])%mod;
}
}
}
}
f[pos][flag][dif]=res[0];
dp[pos][flag][dif]=res[1];
return res;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>m;
root=++tot;
for(int i=1;i<=n;i++) cin>>a[i],Ins(a[i]);
cout<<dfs(29,root,true,false)[1]<<"\n";
return 0;
}