1. 程式人生 > >Xor Sum 01字典樹 hdu4825

Xor Sum 01字典樹 hdu4825

AI panel inf 超過 using 測試數據 sum printf add

Xor Sum

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 4119 Accepted Submission(s): 1796


Problem Description Zeus 和 Prometheus 做了一個遊戲,Prometheus 給 Zeus 一個集合,集合中包含了N個正整數,隨後 Prometheus 將向 Zeus 發起M次詢問,每次詢問中包含一個正整數 S ,之後 Zeus 需要在集合當中找出一個正整數 K ,使得 K 與 S 的異或結果最大。Prometheus 為了讓 Zeus 看到人類的偉大,隨即同意 Zeus 可以向人類求助。你能證明人類的智慧麽?

Input 輸入包含若幹組測試數據,每組測試數據包含若幹行。
輸入的第一行是一個整數T(T < 10),表示共有T組數據。
每組數據的第一行輸入兩個正整數N,M(<1=N,M<=100000),接下來一行,包含N個正整數,代表 Zeus 的獲得的集合,之後M行,每行一個正整數S,代表 Prometheus 詢問的正整數。所有正整數均不超過2^32。

Output 對於每組數據,首先需要輸出單獨一行”Case #?:”,其中問號處應填入當前的數據組數,組數從1開始計算。
對於每個詢問,輸出一個正整數K,使得K與S異或值最大。

Sample Input 2 3 2 3 4 5 1 5 4 1 4 6 5 6 3 Sample Output Case #1: 4 3 Case #2: 4
 1
#include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 #include<queue> 6 #define inf 0x3fffffff 7 #define Memset(x, a) memset(x, a, sizeof(x)) 8 using namespace std; 9 typedef long long LL; 10 const int maxn = 100000 + 5; 11 int tree[32 * maxn][2
]; 12 LL val[32 * maxn]; 13 int sz; 14 void init() { 15 memset(tree[0], 0, sizeof(tree[0])); 16 // Memset(tree[0],0); 17 sz = 1; 18 } 19 void add(LL a) { 20 int u = 0; 21 for (int i = 32 ; i >= 0 ; i--) { 22 int b = ((a >> i) & 1) ; 23 if (!tree[u][b]) { 24 memset(tree[sz], 0, sizeof(tree[sz])); 25 // Memset(tree[sz],0); 26 val[sz] = 0; 27 tree[u][b] = sz++; 28 } 29 u = tree[u][b]; 30 } 31 val[u] = a; 32 } 33 LL query(LL a ) { 34 int u = 0; 35 for (int i = 32; i >= 0 ; i--) { 36 int b = ((a >> i) & 1) ; 37 if (tree[u][b ^ 1]) u = tree[u][b ^ 1]; 38 else u = tree[u][b]; 39 } 40 return val[u]; 41 } 42 int main() { 43 int t, n, m, cas = 1; 44 LL a; 45 scanf("%d", &t); 46 while(t--) { 47 init(); 48 scanf("%d%d", &n, &m); 49 for (int i = 0 ; i < n ; i++) { 50 scanf("%lld", &a); 51 add(a); 52 } 53 printf("Case #%d:\n", cas++); 54 for (int i = 0 ; i < m ; i++) { 55 scanf("%d", &a); 56 printf("%lld\n", query(a)); 57 } 58 } 59 return 0; 60 }

Xor Sum 01字典樹 hdu4825