-
[1597] Find MaxXorSum
- 时间限制: 2000 ms 内存限制: 65535 K
- 问题描述
-
Given n non-negative integers, you need to find two integers a and b that a xor b is maximum. xor is exclusive-or.
- 输入
-
Input starts with an integer T(T <= 10) denoting the number of tests.
For each test case, the first line contains an integer n(n <= 100000), the next line contains a1, a2, a3, ......, an(0 <= ai <= 1000000000); - 输出
-
For each test case, print you answer.
- 样例输入
-
2 4 1 2 3 4 3 7 12 5
- 样例输出
-
7 11
- 提示
-
无
- 来源
-
Alex@NBUT
思路:字典树,将N个数的二进制存到树里,然后再遍历N个数,找到异或的最大值。
# include <iostream> # include <cstdio> # include <cstring> # include <algorithm> # define ll long long using namespace std; const int maxn = 1e5; ll a[maxn+3], cnt=0; struct node { int next[2]; }tri[maxn*13];//乘以13即可,待证。 void add(ll x) { int cur = 0; for(int i=31; i>=0; --i)//题目数据范围为32位整型。 { int t = (x>>i)&1; if(!tri[cur].next[t]) tri[cur].next[t] = ++cnt; cur = tri[cur].next[t]; } } ll query(ll x) { int cur = 0; ll tmp = 0; for(int i=31; i>=0; --i) { int t = !((x>>i)&1);//找到相反的,因为不同的异或值为1。 if(tri[cur].next[t]) { tmp |= (1<<i); cur = tri[cur].next[t]; } else cur = tri[cur].next[!t]; } return tmp; } int main() { int t, n; scanf("%d",&t); while(t--) { cnt = 0; scanf("%d",&n); memset(tri, 0, sizeof(tri)); for(int i=1; i<=n; ++i) { scanf("%lld",&a[i]); add(a[i]); } ll ans = 0; for(int i=1; i<=n; ++i) ans = max(ans, query(a[i])); printf("%lld\n",ans); } return 0; }