CH1602 The XOR Largest Pair Trie树

题目链接

http://noi-test.zzstep.com/contest/0x10%E3%80%8C%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E3%80%8D%E4%BE%8B%E9%A2%98/1602%20The%20XOR%20Largest%20Pair

分析

将每个整数对应的二进制串建成Trie树,在插入一个数前,在Trie树中检索该数,每次尽量沿与当前位不同的走。

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 1e5 + 5;

struct Trie {
	int ch[32 * maxn][2], tot;

	Trie() {
		memset(ch[0], 0, sizeof(ch[0]));
		tot = 0;
	}

	int add() {
		++tot;
		memset(ch[tot], 0, sizeof(ch[tot]));
		return tot;
	}

	void insert(int x) {
		int p = 0;
		for (int i = 30; i >= 0; --i) {
			if (!ch[p][(x >> i) & 1]) ch[p][(x >> i) & 1] = add();
			p = ch[p][(x >> i) & 1];
		}
	}

	int query(int x) {
		int p = 0, ans = 0;
		for (int i = 30; i >= 0; --i) {
			if (!ch[p][(x >> i) & 1] && !ch[p][((x >> i) & 1) ^ 1])
				break;
			if (ch[p][((x >> i) & 1) ^ 1]) {
				p = ch[p][((x >> i) & 1) ^ 1], ans |= 1 << i;
			}
			else p = ch[p][(x >> i) & 1];
		}
		return ans;
	}
} trie;

int main() {
	int n = read(), ans = 0;
	for (int i = 1; i <= n; ++i) {
		int x = read();
		ans = max(ans, trie.query(x));
		trie.insert(x);
	}
	printf("%d", ans);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值