码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4825 字典树

时间:2015-07-26 20:52:06      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

HDU 4825 

对于给定的查询(一个整数),求集合中和他异或值最大的值是多少

按位从高位往低位建树,查询时先将查询取反,然后从高位往低位在树上匹配,可以匹配不可以匹配都走同一条边(匹配表示有一个异或值为1的边,选择当然最好;不能匹配说明不存在一条异或值为1的边,那么只存在一条为0的边,也不得不选)

 1 //#pragma comment(linker, "/STACK:1677721600")
 2 #include <map>
 3 #include <set>
 4 #include <stack>
 5 #include <queue>
 6 #include <cmath>
 7 #include <ctime>
 8 #include <vector>
 9 #include <cstdio>
10 #include <cctype>
11 #include <cstring>
12 #include <cstdlib>
13 #include <iostream>
14 #include <algorithm>
15 using namespace std;
16 #define INF 0x3f3f3f3f
17 #define inf (-((LL)1<<40))
18 #define lson k<<1, L, (L + R)>>1
19 #define rson k<<1|1,  ((L + R)>>1) + 1, R
20 #define mem0(a) memset(a,0,sizeof(a))
21 #define mem1(a) memset(a,-1,sizeof(a))
22 #define mem(a, b) memset(a, b, sizeof(a))
23 #define FIN freopen("in.txt", "r", stdin)
24 #define FOUT freopen("out.txt", "w", stdout)
25 #define rep(i, a, b) for(int i = a; i <= b; i ++)
26 #define dec(i, a, b) for(int i = a; i >= b; i --)
27 
28 template<class T> T MAX(T a, T b) { return a > b ? a : b; }
29 template<class T> T MIN(T a, T b) { return a < b ? a : b; }
30 template<class T> T GCD(T a, T b) { return b ? GCD(b, a%b) : a; }
31 template<class T> T LCM(T a, T b) { return a / GCD(a,b) * b;    }
32 
33 //typedef __int64 LL;
34 typedef long long LL;
35 const int MAXN = 100000 + 100;
36 const int MAXM = 110000;
37 const double eps = 1e-8;
38 LL MOD = 1000000007;
39 
40 const LL H = ((LL)1 << 33) - 1;
41 int t, n, m, num[40], cas = 0;
42 int tree[3400000][2], s;
43 
44 void get_num(LL x) {
45     mem0(num);
46     int id = 0;
47     while(x) {
48         num[id++] = x % 2;
49         x >>= 1;
50     }
51 }
52 
53 void insert_to_tree(LL x)
54 {
55     get_num(x);
56     int u = 0;
57     dec (i, 32, 0) {
58         int c = num[i];
59         if(!tree[u][c]) {
60             tree[u][c] = ++s;
61         }
62         u = tree[u][c];
63     }
64 }
65 
66 int main()
67 {
68 //    FIN;
69     cin >> t;
70     while(t--) {
71         s = 0;
72         mem0(tree);
73         scanf("%d %d", &n, &m);
74         LL x, ans;
75         rep (i, 1, n) {
76             scanf("%lld", &x);
77             insert_to_tree(x);
78         }
79         printf("Case #%d:\n", ++cas);
80         rep (i, 1, m) {
81             scanf("%lld", &x);
82             x = (~x) & H;
83             get_num(x);
84             int u = 0;
85             ans = 0;
86             dec (j, 32, 0) {
87                 int c = num[j];
88                 ans |= (LL)(tree[u][c] ? c : !c) << j;
89                 u = tree[u][c] ? tree[u][c] : tree[u][!c];
90             }
91             printf("%lld\n", ans);
92         }
93     }
94     return 0;
95 }

 

HDU 4825 字典树

标签:

原文地址:http://www.cnblogs.com/gj-Acit/p/4678593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!