版权声明:转载请标明出处 https://blog.csdn.net/weixin_41190227/article/details/89764507
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
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);Output
For each test case, print you answer.
Sample Input
2 4 1 2 3 4 3 7 12 5Sample Output
7 11Hint
无
题目大意:给出一组数,求任意两个数的异或最大值。
解题思路:把每一个数转化成01串构建字典树。最后再对于数组中没个数在字典树中查找最大的异或值是多少即可。
/* @Author: Top_Spirit @Language: C++ */ //#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cstring> using namespace std ; typedef long long ll ; const int Maxn = 1e5 + 10 ; const int Maxn1 = 1e6 + 10 ; const int INF = 0x3f3f3f3f ; ll a[Maxn] ; ll son[Maxn << 4][2] ,cnt ; void init(){ memset(son, 0, sizeof(son)) ; cnt = 0 ; } void Insert(ll k){ ll p = 0 ; for (int i = 31; i >= 0; i--){ ll id = (k >> i) & 1 ; if (!son[p][id]) son[p][id] = ++cnt ; p = son[p][id] ; } } ll Find(ll k){ ll p = 0, ans = 0 ; for (int i = 31; i >= 0; i--){ int id = !((k >> i) & 1) ; ans <<= 1 ; if (son[p][id]) p = son[p][id], ans++ ; else p = son[p][!id] ; } return ans ; } int main (){ ios_base::sync_with_stdio(false) ; cin.tie(0) ; cout.tie(0) ; int T, n ; cin >> T ; while (T--){ init() ; cin >> n ; for (ll i = 1; i <= n; i++){ cin >> a[i] ; Insert(a[i]) ; } ll ans = -1 ; for (int i = 1; i <= n; i++){ ans = max(ans, Find(a[i])) ; } cout << ans << endl ; } return 0 ; }