题解:AT_abc425_g [ABC425G] Sum of Min of XOR
来分享一个神秘做法。赛时写错细节没调出来/fn。
以下位均为二进制位(废话)。
考虑对于每个
假设我们固定一个
于是我们要在叶子节点统计(设分叉位集合为
这个问题可以使用数位 dp 解决。
具体地,我们设 first 为 second 为
如果你充分理解了数位 dp,代码比较好写:
::::success[代码]
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char *p1,*p2,buf[100010];
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read(){
int x=0;
char c=gc();
while(c<48)c=gc();
while(47<c)x=(x<<3)+(x<<1)+(c&15),c=gc();
return x;
}
unsigned char vs[30];
int m,X,Y;
ll ans;
pair<int,ll>f[30][2];
pair<int,ll>solve(int now,unsigned char l){
if(!~now)return make_pair(1,0);
if(~f[now][l].first)return f[now][l];
unsigned char lm=l?m>>now&1:1;
f[now][l]=make_pair(0,0);
pair<int,ll>ret;
if(!vs[now]){
if(l&&(X>>now&1)&&!lm)f[now][l]=make_pair(0,0);
else f[now][l]=solve(now-1,l&&(X>>now&1)==lm);
}else{
for(unsigned char i=0;i<=lm;++i){
ret=solve(now-1,l&&i==lm);
f[now][l].first+=ret.first;
f[now][l].second+=ret.second+(((Y>>now&1)^i)<<now)*(ll)ret.first;
}
}
return f[now][l];
}
struct node{
int ch[2];
}t[6000010];
void dfs(int now,int dep,int w,int w2){
if(!~dep){
memset(f,-1,sizeof f);
X=w;
Y=w2;
ans+=solve(29,1).second;
return;
}
if(!t[now].ch[0]){
vs[dep]=1;
dfs(t[now].ch[1],dep-1,w,w2|1<<dep);
}else if(!t[now].ch[1]){
vs[dep]=1;
dfs(t[now].ch[0],dep-1,w,w2);
}else{
vs[dep]=0;
dfs(t[now].ch[0],dep-1,w,w2);
dfs(t[now].ch[1],dep-1,w|1<<dep,w2|1<<dep);
}
}
int main(){
int n=read(),u,o,tot=0,x;
m=read()-1;
while(n--){
x=read();
u=0;
for(int i=29;~i;--i){
o=x>>i&1;
if(!t[u].ch[o])t[u].ch[o]=++tot;
u=t[u].ch[o];
}
}
dfs(0,29,0,0);
printf("%lld",ans);
return 0;
}
::::