HDU 5536:Chip Factory(01字典树模板)

题目大意:在一个数组中找出 (s[i]+s[j])^s[k] 最大的值,其中 i、j、k 各不相同。

题解:01字典树模板,01字典树就是将数字的二进制表示形式插入字典树中,由于二进制只有两种字符0和1,01字典树的结构变得更简单。01字典树可以得到一个数字在一个数组里和谁异或得到的值最大,做法是贪心匹配,字典树上的每一个结点尽量走字符不同的地方。

这题还要下标不能重复,做法是:将s 序列加入01字典树,枚举s[i] + s[j],删掉字典树上s[i] 和 s[j]的路径,在字典树上查询时就不会走到s[i] 或 s[j],查询完再加回来。可以维护一个结点访问次数,将s[i],s[j]路径上的结点访问次数-1,字典树上匹配时若访问次数为0或不存在这个结点就不能走。

#include<bits/stdc++.h>
using namespace std;
int t,n;
const int maxn = 1e3 + 10;
const int mx = 1e5 + 10;
typedef long long ll;
ll a[maxn],val[mx];
int tot,nxt[mx][2],num[mx];
void init() {
	tot = 1;
	nxt[0][0] = nxt[0][1] = num[0] = val[0] = 0;
}
void insert(ll x) {
	int rt = 0;
	for(int i = 31; i >= 0; i--) {
		int y = ((x >> i) & 1);
		if(!nxt[rt][y]) {
			nxt[rt][y] = tot;
			num[tot] = 0;val[tot] = 0;
			nxt[tot][0] = nxt[tot][1] = 0;
			tot++;
		}
		rt = nxt[rt][y];
		num[rt]++;
	}
	val[rt] = x;
}
void upd(ll x,int v) {
	int rt = 0;
	for(int i = 31; i >= 0; i--) {
		int y = ((x >> i) & 1);
		rt = nxt[rt][y];
		num[rt] += v;
	}	
}
ll qry(ll x) {
	int rt = 0;
	for(int i = 31; i >= 0; i--) {
		int y = ((x >> i) & 1);
		if(nxt[rt][y ^ 1] && num[nxt[rt][y ^ 1]]) rt = nxt[rt][y ^ 1];
		else rt = nxt[rt][y];
	}
	return val[rt] ^ x;
}
int main() {
	scanf("%d",&t);
	while(t--) {
		scanf("%d",&n);
		init();
		for(int i = 1; i <= n; i++) scanf("%lld",&a[i]),insert(a[i]);
		ll ans = 0;
		for(int i = 1; i <= n; i++)
			for(int j = 1; j <= n; j++) {
				if(i==j)continue;
				upd(a[i],-1);upd(a[j],-1);
				ans = max(ans,qry(a[i] + a[j]));
				upd(a[i],1);upd(a[j],1);
			}
		printf("%lld\n",ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值