HDU4825 Xor Sum —— Trie树
生活随笔
收集整理的這篇文章主要介紹了
HDU4825 Xor Sum —— Trie树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:https://vjudge.net/problem/HDU-4825
?
Xor Sum
Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 3839????Accepted Submission(s): 1685
?
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?
Source 2014年百度之星程序設計大賽 - 資格賽?
Recommend liuyiding?
題解:
將所有數按二進制從高位到低位插入到Trie樹中,然后再枚舉每一個數,去Trie中反向匹配即可。
?
代碼如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <vector> 6 #include <cmath> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <set> 12 using namespace std; 13 typedef long long LL; 14 const int INF = 2e9; 15 const LL LNF = 9e18; 16 const int MOD = 1e9+7; 17 const int MAXN = 1e5+10; 18 19 struct Trie 20 { 21 int next[33*MAXN][2]; 22 int root, L = 0; 23 int newnode() 24 { 25 next[L][0] = next[L][1] = -1; 26 L++; 27 return L-1; 28 } 29 void init() 30 { 31 L = 0; 32 root = newnode(); 33 } 34 void insert(LL val) 35 { 36 int tmp = root, way; 37 for(int i = 32; i>=0; i--) 38 { 39 way = (val>>i)&1; 40 if(next[tmp][way]==-1) next[tmp][way] = newnode(); 41 tmp = next[tmp][way]; 42 } 43 } 44 LL query(LL val) 45 { 46 LL ret = 0; 47 int tmp = root, way; 48 for(int i = 32; i>=0; i--) 49 { 50 ret <<= 1; 51 way = (val>>i)&1; 52 if(next[tmp][!way]!=-1) //如果另一方向存在,則走另一方向 53 ret ^= !way, tmp = next[tmp][!way]; 54 else //否則,順著走 55 ret ^= way, tmp = next[tmp][way]; 56 } 57 return ret; 58 } 59 }; 60 Trie T; 61 62 int main() 63 { 64 int n, m, TT; 65 scanf("%d",&TT); 66 for(int kase = 1; kase<=TT; kase++) 67 { 68 scanf("%d%d",&n,&m); 69 T.init(); 70 for(int i = 1; i<=n; i++) 71 { 72 LL val; 73 scanf("%lld",&val); 74 T.insert(val); 75 } 76 77 printf("Case #%d:\n",kase); 78 while(m--) 79 { 80 LL val; 81 scanf("%lld",&val); 82 printf("%lld\n", T.query(val)); 83 } 84 } 85 } View Code?
轉載于:https://www.cnblogs.com/DOLFAMINGO/p/8727860.html
總結
以上是生活随笔為你收集整理的HDU4825 Xor Sum —— Trie树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django学习笔记(一):第一个dja
- 下一篇: mui 打开openWindow新页面不