首页 > 代码库 > HDOJ4825-Xor Sum(贪心 + Trie + 位运算)
HDOJ4825-Xor Sum(贪心 + Trie + 位运算)
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
23 23 4 5154 14 6 5 63
Sample Output
Case #1:43Case #2:4
Code:
1 #include <bits/stdc++.h> 2 using namespace std; 3 int t; 4 typedef long long LL; 5 int n , m; 6 struct Node 7 { 8 Node* next[2]; 9 Node()10 {11 memset(next , NULL , sizeof(next));12 }13 };14 15 void Insert(int s , Node* root)16 {17 Node* p = root;18 for(int i = 31 ; i >= 0 ; --i)19 {20 int id = ((s & (1 << i)) != 0);21 if(p->next[id] == NULL)22 p->next[id] = new Node();23 p = p->next[id];24 }25 }26 int Query(int s , Node* root)27 {28 Node* p = root;29 int ans = 0;30 for(int i = 31 ; i >= 0 ; --i)31 {32 int id = ((s & (1 << i)) != 0);33 if(p->next[id ^ 1])34 ans |= (id ^ 1) << i , p = p->next[id ^ 1];35 else36 ans |= id << i , p = p->next[id];37 }38 return ans;39 }40 int main()41 {42 scanf("%d" , &t);43 for(int c = 1 ; c <= t ; ++c)44 {45 Node* root = new Node();46 scanf("%d%d" , &n , &m);47 int x;48 for(int i = 1 ; i <= n ; ++i)49 {50 scanf("%d" , &x);51 Insert(x , root);52 }53 54 printf("Case #%d:\n" , c);55 while(m--)56 {57 scanf("%d" , &x);58 printf("%d\n" , Query(x , root));59 }60 }61 }
HDOJ4825-Xor Sum(贪心 + Trie + 位运算)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。