Xor Sum (字典树求异或)

Xor Sum (字典树求异或)

题目大意:给出n个数,然后m次查询,问每次要查询的数与这n个数异或最大的值是哪个

解题思路:很显然这是一道字典树求异或的模板题,是POJ 3764的简化版,详细见我的另一篇博客

Code:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int MAXN = 100100;
int t[MAXN*33][3],tot = 1,D[MAXN];
int head[MAXN],cnt = 1;
bool vis[MAXN];



void insert(int x){                         //插入到字典树
    int p=1;
    for(int k=31;k>=0;k--){               //转换成01串
        int ch =x>>k&1;                      // if(x&(1<<i)) ch=1; else ch=0;
        if(t[p][ch]==0){
        	t[p][ch]=++tot;
		} 
        p = t[p][ch];
    }
}

int search(int x){
    int p = 1,ans = 0;
    for(int k = 31;k >= 0;k--){
        int ch = x>>k&1;
        if(t[p][!ch]){                     //尽可能找不一样的,贪心思想
            p = t[p][!ch];
            ans |= 1<<k;
        }else p = t[p][ch];
    }
    return ans;
}


int main(){
    int n,m,T,w,ans;
    scanf("%d",&T);
    for(int k=1;k<=T;k++){
    	memset(t,0,sizeof t);
    	scanf("%d%d",&n,&m);
    	for(int i=1;i<=n;i++){
    		scanf("%d",&w);
    		insert(w);
		}
		printf("Case #%d:\n",k);
		for(int i=1;i<=m;i++){
			scanf("%d",&w);
			ans=search(w);
			printf("%d\n",ans^w);       //不是求异或和,要异或回来
		}
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43872264/article/details/107658738