-
Notifications
You must be signed in to change notification settings - Fork 312
/
max_xor.py
47 lines (42 loc) · 998 Bytes
/
max_xor.py
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
"""
Maximizes xor of values in a list (works with big integers)
Example:
>>>> A = [10**20, 3, 6, 4]
>>>> I = max_xor(A)
>>>> xor = 0
>>>> for i in I:
.... xor ^= A[i]
....
>>>> xor
100000000000000000007
"""
def max_xor(A):
"""
Input:
List A of non-negative integers
Output:
I such that xor(A[i] for i in I) is maximized
"""
base = []
how = {}
reduced_base = {}
for i in range(len(A)):
a = A[i]
tmp = 0
while a:
b = a.bit_length() - 1
if b in reduced_base:
a ^= reduced_base[b]
tmp ^= how[b]
else:
reduced_base[b] = a
how[b] = tmp | (1 << len(base))
base.append(i)
break
x = 0
tmp = 0
for j in sorted(reduced_base, reverse=True):
if not x & (1 << j):
x ^= reduced_base[j]
tmp ^= how[j]
return [base[j] for j in range(len(base)) if tmp & (1 << j)]