Skip to content

Commit c23f6b5

Browse files
authored
Create binary_trie.py
Useful in Competitive Programming. Contains method to find maximum and minimum XOR value.
1 parent e9e7c96 commit c23f6b5

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

data_structures/trie/binary_trie.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class BinaryTrie:
2+
def __init__(self, max_bit_len=31):
3+
self.inf = 1 << 63
4+
self.cc = [0]
5+
self.to = [[-1], [-1]]
6+
self.mb = max_bit_len
7+
8+
def add(self, a):
9+
u = 0
10+
self.cc[u] += 1
11+
for i in range(self.mb-1, -1, -1):
12+
d = a >> i & 1
13+
if self.to[d][u] == -1:
14+
self.to[d][u] = len(self.cc)
15+
self.to[0].append(-1)
16+
self.to[1].append(-1)
17+
self.cc.append(0)
18+
u = self.to[d][u]
19+
self.cc[u] += 1
20+
21+
def remove(self, a):
22+
if self.cc[0] == 0: return False
23+
uu = [0]
24+
u = 0
25+
for i in range(self.mb-1, -1, -1):
26+
d = a >> i & 1
27+
u = self.to[d][u]
28+
if u == -1 or self.cc[u] == 0: return False
29+
uu.append(u)
30+
for u in uu: self.cc[u] -= 1
31+
return True
32+
33+
def cnt(self, a):
34+
u = 0
35+
for i in range(self.mb-1, -1, -1):
36+
d = a >> i & 1
37+
u = self.to[d][u]
38+
if u == -1 or self.cc[u] == 0: return 0
39+
return self.cc[u]
40+
41+
def min_xor(self, a):
42+
if self.cc[0] == 0: return self.inf
43+
u, res = 0, 0
44+
for i in range(self.mb-1, -1, -1):
45+
d = a >> i & 1
46+
v = self.to[d][u]
47+
if v == -1 or self.cc[v] == 0:
48+
res |= 1 << i
49+
u = self.to[d ^ 1][u]
50+
else:
51+
u = v
52+
return res
53+
54+
def max_xor(self, a):
55+
if self.cc[0] == 0: return -self.inf
56+
u, res = 0, 0
57+
for i in range(self.mb-1, -1, -1):
58+
d = a >> i & 1
59+
v = self.to[d ^ 1][u]
60+
if v == -1 or self.cc[v] == 0:
61+
u = self.to[d][u]
62+
else:
63+
u = v
64+
res |= 1 << i
65+
return res

0 commit comments

Comments
 (0)