1. 程式人生 > >CH1602 The XOR Largest Pair【Trie樹】

CH1602 The XOR Largest Pair【Trie樹】

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 }