hdu 4825 Xor Sum 位操作 字典树

遇到本题,在对象成员中申请数组空间的话,会不明就里地TLE,而且浪费大量内存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 2015年7月15日 上午11:21:15
* PrjName:hdu4825
* @ Semprathlon
*/

import java.io.*;

class Trie {
private final int maxd = 33;
private long data;
private Trie ch0, ch1;

void insert(long n) {
Trie rt = this;
for (int i = maxd - 1; i >= 0; i--) {
if ((n & (1L << i)) == 0L) {// 0
if (rt.ch0 == null)
rt.ch0 = new Trie();
rt = rt.ch0;
} else {// 1
if (rt.ch1 == null)
rt.ch1 = new Trie();
rt = rt.ch1;
}
if (i == 0)
rt.data = n;
}
}

long query(long n) {
Trie rt = this;
for (int i = maxd - 1; i >= 0; i--) {
if ((n & (1L << i)) > 0L && rt.ch0 != null || rt.ch1 == null)// 0
rt = rt.ch0;
else if (rt.ch1 != null)// 1
rt = rt.ch1;
}
return rt.data;
}
}

public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int cas = 0;
in.nextToken();
int T = (int) in.nval;
while (T-- > 0) {
Trie tr = new Trie();
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
for (int i = 1; i <= n; i++) {
in.nextToken();
tr.insert((long) in.nval);
}
out.println("Case #" + (++cas) + ":");
for (int i = 1; i <= m; i++) {
in.nextToken();
out.println(tr.query((long) in.nval));
}
}
out.flush();
out.close();
}

}

hdu 4825 Xor Sum 位操作 字典树

https://devblog.citruxonve.net/posts/c79f0e32/

Author

Semprathlon / Simfae Dean

Posted on

07/17/2015

Updated on

07/19/2023

Licensed under

Comments