1. 程式人生 > >【trie樹】HDU4825 Xor Sum

【trie樹】HDU4825 Xor Sum

Xor Sum
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 5864    Accepted Submission(s): 2557


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 Source 2014年百度之星程式設計大賽 - 資格賽 Recommend liuyiding
T

這道題是道字典樹的題,是為什麼呢?

首先看資料範圍,字符集肯定是2,因為是異或

然後我們可以把每個數變成一個32位的二進位制數(因為資料範圍是2^32),然後插入到字典樹裡,然後查詢時候儘量走和詢問數那一位不一樣的路徑

最後累加就是答案;

怎麼 把這個數二進位制化呢,只要列舉第幾位然後把這個數和1<<i位&一下就好了

這道題有一個東西

1<<0=1

1<<31=-2147483648

1<<32=0

這就很尷尬,因為這道題資料範圍裡可能會有三十二位

所以

1ll<<31=2147483648

1ll<<32=4294967296

這裡加了一個ll,意味著告訴計算機這個1是個ll的型別

程式碼在此

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #define N 100011
 5 using namespace std;
 6 int t,n,m;
 7 long long s;
 8 long long num[N];
 9 int cnt=1;
10 struct trie{
11     int to[2],val;
12 }tree[35*N];
13 inline void cl(){cnt=1,memset(&tree,0,sizeof(tree));}
14 inline int regist(){return cnt++;}
15 void insert(long long now)
16 {
17     int rt=0;long long c;
18     for(int i=32;i>=0;i--)
19     {
20         c=(1ll<<i)&now;
21         if(c)c=1;
22         if(!tree[rt].to[c])
23             tree[rt].to[c]=regist();
24         rt=tree[rt].to[c];
25     }
26 }
27 long long find(long long now)
28 {
29     int rt=0;long long c,ans=0;
30     for(int i=32;i>=0;i--)
31     {
32         c=(1ll<<i)&now;
33         if(c)c=1;
34         if(tree[rt].to[c^1])
35         {
36             rt=tree[rt].to[c^1];
37             if(c^1)ans+=(1<<i);
38         }
39         else 
40         {
41             rt=tree[rt].to[c];
42             if(c)ans+=(1<<i);
43         }
44     }
45     return ans;
46 }
47 int main()
48 {
49     scanf("%d",&t);
50     int tt=t;
51     while(t--)
52     {
53         cl();
54         scanf("%d%d",&n,&m);
55         for(int i=1;i<=n;i++)
56         {
57             scanf("%lld",&num[i]);
58             insert(num[i]);
59         }
60         printf("Case #%d:\n",tt-t);
61         for(int i=1;i<=m;i++)
62         {
63             scanf("%lld",&s);
64             printf("%lld\n",find(s));
65         }        
66     }
67     return 0;
68 }