Vitya and Strange Lesson (Codeforces 842D)
Tags: Others, binary search

Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.Vitya quickly understood all tasks of the teacher, but can you do the same?You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps:  Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x.  Find mex of the resulting array. Note that after each query the array changes.

Input: First line contains two integer numbers n and m (1 ≤ n, m ≤ 3·105) — number of elements in array and number of queries.Next line contains n integer numbers ai (0 ≤ ai ≤ 3·105) — elements of then array.Each of next m lines contains query — one integer number x (0 ≤ x ≤ 3·105).

Output: For each query print the answer on a separate line.


Sample Inputs:
2 2
1 3
1
3

4 3
0 1 5 6
1
2
4

5 4
0 1 5 6 7
1
1
4
5

Sample Outputs:
1
0

2
0
0

2
2
0
2

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binary_trie():
    (G0, G1, cnt) = ([-1], [-1], [0])
    return (G0, G1, cnt)

def insert(x, l):
    j = 0
    for i in range(l, -1, -1):
        cnt[j] += 1
        if x & pow2[i]:
            if G1[j] == -1:
                G0.append(-1)
                G1.append(-1)
                cnt.append(0)
                G1[j] = len(cnt) - 1
            j = G1[j]
        else:
            if G0[j] == -1:
                G0.append(-1)
                G1.append(-1)
                cnt.append(0)
                G0[j] = len(cnt) - 1
            j = G0[j]
    cnt[j] += 1
    return

def xor_and_count_min(x, k, l):
    j = 0
    ans = 0
    for i in range(l, -1, -1):
        if not x & pow2[i]:
            if k & pow2[i]:
                if G0[j] ^ -1:
                    ans += cnt[G0[j]]
                j = G1[j]
            else:
                j = G0[j]
        elif k & pow2[i]:
            if G1[j] ^ -1:
                ans += cnt[G1[j]]
            j = G0[j]
        else:
            j = G1[j]
    return ans

def binary_search(c1, c2):
    m = (c1 + c2) // 2
    while abs(c1 - c2) > 1:
        m = (c1 + c2) // 2
        if ok(m):
            c1 = m
        else:
            c2 = m
    m += 1
    while not ok(m):
        m -= 1
    return m

def ok(m):
    return True if xor_and_count_min(now, m, l) == m else False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
(G0, G1, cnt) = binary_trie()
l = 20
pow2 = [1]
for _ in range(l):
    pow2.append(2 * pow2[-1])
for i in set(a):
    insert(i, l)
ans = []
u = [-1] * pow2[l]
now = 0
for _ in range(m):
    x = int(input())
    now ^= x
    if u[now] == -1:
        z = binary_search(0, pow2[19])
        u[now] = z
    ans0 = u[now]
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binary_trie():
    (G0, G1, cnt) = ([-1], [-1], [0])
    return (G0, G1, cnt)

def insert(x, l):
    j = 0
    for i in range(l, -1, -1):
        cnt[j] += 1
        if x & pow2[i]:
            if G1[j] == -1:
                G0.append(-1)
                G1.append(-1)
                cnt.append(0)
                G1[j] = len(cnt) - 1
            j = G1[j]
        else:
            if G0[j] == -1:
                G0.append(-1)
                G1.append(-1)
                cnt.append(0)
                G0[j] = len(cnt) - 1
            j = G0[j]
    cnt[j] += 1
    return

def xor_and_count_min(x, k, l):
    j = 0
    ans = 0
    for i in range(l, -1, -1):
        if not x & pow2[i]:
            if k & pow2[i]:
                if G0[j] ^ -1:
                    ans += cnt[G0[j]]
                j = G1[j]
            else:
                j = G0[j]
        elif k & pow2[i]:
            if G1[j] ^ -1:
                ans += cnt[G1[j]]
            j = G0[j]
        else:
            j = G1[j]
    return ans

def binary_search(c1, c2):
    m = (c1 + c2) // 2
    while abs(c1 - c2) > 1:
        m = (c1 + c2) // 2
        if ok(m):
            c1 = m
        else:
            c2 = m
    m += 1
    while not ok(m):
        m -= 1
    return m

def ok(m):
    return True if xor_and_count_min(now, m, l) == m else False
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
(G0, G1, cnt) = binary_trie()
l = 20
pow2 = [1]
for _ in range(l):
    pow2.append(2 * pow2[-1])
for i in set(a):
    insert(i, l)
ans = []
u = [-1] * pow2[l]
now = 0
for _ in range(m):
    x = int(input())
    now ^= x
    if u[now] == -1:
        z = binary_search(0, pow2[19])
        u[now] = z
    ans0 = u[now]
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class Trie:

    class Node:

        def __init__(self, char: bool=False):
            self.char = char
            self.children = []
            self.counter = 1

    def __init__(self):
        self.root = Trie.Node()

    def add(self, word):
        node = self.root
        for char in word:
            found_in_child = False
            for child in node.children:
                if child.char == char:
                    child.counter += 1
                    node = child
                    found_in_child = True
                    break
            if not found_in_child:
                new_node = Trie.Node(char)
                node.children.append(new_node)
                node = new_node

    def query(self, prefix, root=None):
        if not root:
            root = self.root
        node = root
        if not root.children:
            return 0
        prefix = [prefix]
        for char in prefix:
            char_not_found = True
            for child in node.children:
                if child.char == char:
                    char_not_found = False
                    node = child
                    break
            if char_not_found:
                return 0
        return node
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
tr = Trie()
st = set()
for i in a:
    if i in st:
        continue
    else:
        st.add(i)
    x = bin(i)[2:]
    x = '0' * (20 - len(x)) + x
    x = [True if k == '1' else False for k in x]
    tr.add(x)

def f(x):
    x = bin(x)[2:]
    x = '0' * (20 - len(x)) + x
    x = [True if k == '1' else False for k in x]
    node = tr.root
    ans = 0
    for i in range(20):
        cur = x[i]
        next = tr.query(cur, node)
        if next and next.counter == 2 ** (19 - i):
            node = tr.query(not cur, node)
            ans += 2 ** (19 - i)
        else:
            node = next
    return ans
cur = -1
for _ in range(m):
    if cur == -1:
        cur = int(input())
    else:
        cur = cur ^ int(input())
    print(f(cur))