版权声明:希望能在自己成长的道路上帮到更多的人,欢迎各位评论交流 https://blog.csdn.net/yiqzq/article/details/81842440
原题地址:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1216
题意:给定一些数,求这些数中两个数的异或值最大的那个值
思路:字典树的运用,每一次贪心的去找所需要的数字,用ret保存路上经过节点的信息
具体看代码:
#include <bits/stdc++.h>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <cctype>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<11
#define CLR(x,y) memset((x),y,sizeof(x))
#define fuck(x) cerr << #x << "=" << x << endl
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
int n, pos; //字典树节点标号
int trie[maxn][2];
void Insert(ll x) {//插入操作
int root = 0;
for (int i = 31; i >= 0; i--) { //32位整数
int a = (x >> i) & 1;
if (trie[root][a] == 0) {
trie[root][a] = pos++;
}
root = trie[root][a];
}
}
ll a[maxn];
ll Find(ll x) {
int root = 0;
ll ret = 0; //收集路径上的信息,最后输出结果
for (int i = 31; i >= 0; i--) {
int need = !((x >> i) & 1);
ret <<= 1;
if (trie[root][need]) {
root = trie[root][need];
ret++;//如果需要的值存在,那么该位异或之后一定是1
} else root = trie[root][!need];//不存在的话往树另一边走
}
return ret;//最后查询出来的就是两个数的异或值
}
int main() {
while (~scanf("%d", &n)) {
pos = 1;
CLR(trie, 0);
for (int i = 1; i <= n; i++) {
scanf("%lld", &a[i]);
Insert(a[i]);
}
ll MAX = 0;
for (int i = 1; i <= n; i++) {
MAX = max(MAX, Find(a[i]));
}
printf("%lld\n", MAX);
}
return 0;
}