1602 The XOR Largest Pair 0x10「基本数据结构」例题
描述
在给定的N个整数A1,A2……AN中选出两个进行xor运算,得到的结果最大是多少?
输入格式
第一行一个整数N,第二行N个整数A1~AN。
输出格式
一个整数表示答案。
样例输入
3 1 2 3
样例输出
3
数据范围与约定
- 对于100%的数据: N<=10^5, 0<=Ai<2^31。
思路:
把一个整数看作长度是32的二进制01串。
要找到异或最大的一对,就是要沿着与当前位相反的字符指针往下访问。如果没有相反的就取相同的。
每加入一个数,就查询一次。
1 #include <iostream> 2 #include <set> 3 #include <cmath> 4 #include <stdio.h> 5 #include <cstring> 6 #include <algorithm> 7 #include <map> 8 using namespace std; 9 typedef long long LL; 10 #define inf 0x7f7f7f7f 11 12 const int maxn = 1e6 + 5; 13 int n, tot = 1; 14 int trie[maxn * 32 + 5][3], ed[maxn]; 15 16 void insertt(int x) 17 { 18 /*int str[34]; 19 int len = 0; 20 while(len < 33){ 21 str[len++] = x & 1; 22 x >>= 1; 23 }*/ 24 int p = 1; 25 for(int i = 30; i >= 0; i--){ 26 int ch = x >> i & 1; 27 if(trie[p][ch] == 0){ 28 trie[p][ch] = ++tot; 29 } 30 p = trie[p][ch]; 31 } 32 //ed[p] = true; 33 } 34 35 int searchh(int x) 36 { 37 /*int len = 0; 38 int str[34]; 39 while(len < 33){ 40 str[len++] = x & 1; 41 x >>= 1; 42 }*/ 43 int p = 1, ans = 0; 44 for(int i = 30; i >= 0; i--){ 45 int ch = x >> i & 1; 46 if(trie[p][ch ^ 1]){ 47 p = trie[p][ch ^ 1]; 48 ans |= 1 << i; 49 } 50 else{ 51 p = trie[p][ch]; 52 } 53 } 54 return ans; 55 } 56 57 int main() 58 { 59 scanf("%d", &n); 60 int ans = 0; 61 for(int i = 0; i < n; i++){ 62 int x; 63 scanf("%d", &x); 64 insertt(x); 65 ans = max(ans, searchh(x)); 66 } 67 printf("%d\n", ans); 68 return 0; 69 }