HDU 4825 Xor Sum (01字典树模板题)
来源:互联网 发布:js按钮点击事件隐藏 编辑:程序博客网 时间:2024/06/06 00:00
题意:给你n个数,然后q次询问,每次询问让你找指定值x与n个数中的哪个数异或后最大。
01字典树的实现可以看成是把一个数的二进制字符化后插入到一颗一般的字典树中
比如在01字典树种插入3时 相当于在字典树中插入00 …..00011(一共32位,这个根据具体问题)
查找最大异或值的时候我们是从最高位 向下贪心查找 贪心策略为:当前查找第k位 二进制数位IDX 如果存在IDX ^ 1的节点 我们就进入这个
节点 否则进入IDX节点 贪心策略的证明: 如果这时我们进入了第K位为IDX 的节点 那么 第k位为IDX ^ 1 的节点组成的数 异或X一定更大
链表代码:#include <iostream>#include <cstring>#include <cstdio>using namespace std;struct node{ int val; node *next[2]; node() { val = 0; memset(next, 0, sizeof(next)); }};node *rt;void build(int x){ node *cur = rt; for(int i = 31; i >= 0; i--) { int num = (x>>i)&1; if(!cur->next[num]) { node *tmp = new node; cur->next[num] = tmp; cur = tmp; } else cur = cur->next[num]; } cur->val = x;}int query(int x){ node *cur = rt; for(int i = 31; i >= 0; i--) { int num = (x>>i)&1; if(cur->next[num^1]) cur = cur->next[num^1]; else cur = cur->next[num]; } return cur->val;}void Delete(node *cur){ for(int i = 0; i < 2; i++) if(cur->next[i]) Delete(cur->next[i]); delete cur;}int main(){ int t, ca = 1, n, q, x; cin >> t; while(t--) { rt = new node; scanf("%d %d", &n, &q); for(int i = 1; i <= n; i++) scanf("%d", &x), build(x); printf("Case #%d:\n", ca++); while(q--) { scanf("%d", &x); printf("%d\n", query(x)); } Delete(rt); } return 0;}
阅读全文
1 0
- HDU 4825 Xor Sum (01字典树模板题)
- HDU 4825 Xor Sum (01字典树模板题)
- HDU 4825 Xor Sum 01字典树模板
- 【01字典树】HDU 4825 Xor Sum
- HDU 4825 Xor Sum 01字典树
- HDU 4825 Xor Sum (01字典树)
- HDU 4825 Xor Sum(01字典树)
- HDU 4825 Xor Sum 【01字典树】
- hdu Xor Sum 4825 01字典树
- hdu 4825 Xor Sum(字典树)
- hdu 4825 Xor Sum(字典树)
- HDU-4825-Xor Sum【字典树】
- Hdu 4825 Xor Sum【字典树+贪心】
- hdu 4825 Xor Sum(字典树)
- hdu 4825 Xor Sum (字典树)
- HDU-Xor Sum(01字典树)
- HDU 4825 Xor Sum (01字典树)
- hdu 4825 Xor Sum 01字典树(入门)
- 让axios发送表单请求形式的键值对post数据
- CF 55D 离散化各个位数的倍数
- C++模版类的声明与定义
- 重定向与管道命令
- 剑指offer 练习四(Java版)
- HDU 4825 Xor Sum (01字典树模板题)
- hdu1596 find the safest road(DijKstra模板简单变形)
- 微信小程序制作表格代码
- maven设置了bootclasspath
- nginx+tomcat+memcache配置
- 第11期 《精品干货》2017年7月刊
- Error:Execution failed for task ':app:compileReleaseJavaWithJavac'
- http和https的区别
- python 动态导入 __import__()函数