java字典树 dp_Find MaxXorSum 字典树+DP

按二进制0,1建树,建好之后树上DP

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

#define INF 0x3f3f3f3f

#define mem(x,y) memset(x,y,sizeof(x))

typedef long long LL;

#define maxn 2222222

#define lson l,m,rt<<1

#define rson m+1,r,rt<<1|1

int n,rear,root;

struct Node {

int son[2];//son【0】代表去往二进制的0位,son【1】同理

int x;//标记这个节点代表0,还是1

int ii;//标记这个节点是二进制的第几位

} node[maxn];

int tree_new() {

rear++;

node[rear].son[0]=node[rear].son[1]=node[rear].x=node[rear].ii=0;

return rear;

}

//初始化树

void tree_init() {

rear=0;

root=tree_new();

}

void tree_insert(int x) {

int rt=root;

for(int i=30; i>=0; i--) {//10亿共有31位01进制可用,

bool t=x&(1<

if(node[rt].son[t]==0) node[rt].son[t]=tree_new();

rt=node[rt].son[t];

node[rt].ii=i;

node[rt].x=t;

// cout<

}

}

int dp(int rt0,int rt1) {//从根节点DP;

if(node[rt0].son[0]==0&&node[rt0].son[1]==0)

return node[rt0].x^node[rt1].x;

int max1=0,max2=0,t=((node[rt0].x^node[rt1].x)<

if(node[rt0].son[0]==0) return t+dp(node[rt0].son[1],node[rt1].son[node[rt1].son[0]?0:1]);

else if(node[rt0].son[1]==0) return t+dp(node[rt0].son[0],node[rt1].son[node[rt1].son[1]?1:0]);

else if (node[rt1].son[1]==0) return t+dp(node[rt1].son[0],node[rt0].son[node[rt0].son[1]?1:0]);

else if (node[rt1].son[0]==0) return t+dp(node[rt1].son[1],node[rt0].son[node[rt0].son[0]?0:1]);

else return t+max(dp(node[rt0].son[0],node[rt1].son[1]),dp(node[rt1].son[0],node[rt0].son[1]));

}

int main() {

//freopen("input.txt","r",stdin);

int T;

scanf("%d",&T);

while(T--) {

tree_init();

scanf("%d",&n);

int a;

for(int i=0; i

scanf("%d",&a);

tree_insert(a);

}

printf("%d\n",dp(root,root));

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值