1. 程式人生 > >HDU-4825 Xor Sum 【字典樹+位異或

HDU-4825 Xor Sum 【字典樹+位異或

B - Xor Sum

Time Limit:1000MS Memory Limit:132768KB 64bit IO Format:%I64d & %I64u
 
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

解題思路:應為要求詢問的數和原來序列中那個數的異或值最大,所以可以想,把數轉換成二進位制儲存在字典樹中,高位數在父節點,然後從高往下找,因為是從最高位開始找的,所以第一個(二進位制相同位數不同的數字)肯定是異或值最大的,然後順著繼續找,迴圈上面步驟,就可以找的

具體看程式碼:

#include<cstdio>
#include<cstring>
#include<string>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<math.h>
#include<map>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef __int64 ll;
const int N=2;

typedef struct Node
{
    int count;
    Node *Next[N];
}Node;

void transformm(ll x,ll a[])//轉換成二進位制數並且用陣列儲存
{
    for(ll i=0;i<32;i++)
        a[i]=(x>>(32-i-1))&1;
}

Node * build()//建立節點
{
    Node *node=(Node *)malloc(sizeof(Node));
    node->count=0;
    memset(node->Next,0,sizeof(node->Next));
    return node;
}

void tire_insert(Node *root,ll a[])//插入數字的二進位制於字典書中
{
    Node *p=root;
    ll i=0;
    while(i<32)
    {
        if(p->Next[a[i]]==NULL)
            p->Next[a[i]]=build();
        p=p->Next[a[i]];
        i++;
        p->count+=1;
    }
}

ll found(Node *root,ll a[])
{
    Node *p=root;
    ll i=0,ans=0;
    while(i<32)
    {
        if(p->Next[!a[i]]!=NULL)
        {
            ans+=!a[i]*(1<<(32-i-1));
            p=p->Next[!a[i]];
        }
        else if(p->Next[a[i]]!=NULL)
        {
            ans+=a[i]*(1<<(32-i-1));
            p=p->Next[a[i]];
        }
        i++;
    }
    return ans;
}

int main()
{
    int T,cas=0;
    scanf("%d",&T);
    while(T--)
    {
        ll tmp,a[32],i;//a[]儲存二進位制數
        int n,m;
        scanf("%d %d",&n,&m);
        Node *root=build();//建立根節點
        while(n--)
        {
            scanf("%I64d",&tmp);
            transformm(tmp,a);
            tire_insert(root,a);
        }
        printf("Case #%d:\n",++cas);
        while(m--)
        {
            scanf("%I64d",&tmp);
            transformm(tmp,a);
            printf("%I64d\n",found(root,a));
        }
    }
    return 0;
}