zoukankan      html  css  js  c++  java
  • HDU

    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

    题解:

    01字典树,把一个数按位从高到低当成字符串存进字典树中,之后根据各种题意来操作。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cstdlib>
    #include <algorithm>
    
    using namespace std;
    
    char s[15];
    
    typedef struct Node* node;
    
    struct Node
    {
    	int val;
    	node Next[2];
    	Node()
    	{
    		val = 0;
    		memset(Next,NULL,sizeof(Next));
    	}
    };
    
    void Insert(node root,int x)
    {
    	node p = root;
    	for(int i=31 ; i>=0 ; i--)
    	{
    		int t = (x>>i)&1;
    		if(p->Next[t] == NULL)p->Next[t] = new struct Node();
    		p = p->Next[t]; 
    	}
    	p->val = x;
    }
    
    int Judge(node root,int x)
    {
    	node p = root;
    	for(int i=31 ; i>=0 ; i--)
    	{
    		int t = ((x>>i)&1)^1;
    		if(p->Next[t] == NULL)t = (x>>i)&1;
    		if(p->Next[t])p = p->Next[t];
    		else return -1;
    	}
    	return p->val;
    } 
    
    void Del(node root){
    	for(int i=0 ; i<2 ; ++i){
    		if(root->Next[i])Del(root->Next[i]);
    	}
    	delete(root);
    }
    
    int main(){
    	
    	int T,N,M;
    	scanf("%d",&T);
    	for(int _=1 ; _<=T ; ++_){
    		printf("Case #%d:
    ",_);
    		node root = new struct Node();
    		scanf("%d %d",&N,&M);
    		for(int i=0 ; i<N ; ++i){
    			int t;
    			scanf("%d",&t);
    			Insert(root,t);
    		}
    		for(int i=0 ; i<M ; ++i){
    			int t;
    			scanf("%d",&t);
    			int m = Judge(root,t);
    			printf("%d
    ",m);
    		}
    		Del(root);
    	}
    	
    	return 0;
    }

  • 相关阅读:
    页面布局
    Vue学习指南
    《前端JavaScript重点》学习笔记 6-12
    复习3----作用域和闭包
    复习1-变量类型和计算
    复习2--js原型与原型链2
    慕课网《前端JavaScript面试技巧》学习笔记(2)-原型和原型链
    旋转图片
    UITextView添加行距
    YYKit之YYText
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514068.html
Copyright © 2011-2022 走看看