Maximum And Queries (hard version) (Codeforces 1903D2)
Tags: Greedy, divide and conquer

This is the hard version of the problem. The only difference between the two versions is the constraint on $$$n$$$ and $$$q$$$, the memory and time limits. You can make hacks only if all versions of the problem are solved.Theofanis really likes to play with the bits of numbers. He has an array $$$a$$$ of size $$$n$$$ and an integer $$$k$$$. He can make at most $$$k$$$ operations in the array. In each operation, he picks a single element and increases it by $$$1$$$.He found the maximum bitwise AND that array $$$a$$$ can have after at most $$$k$$$ operations.Theofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of $$$k$$$.Help Theofanis by calculating the maximum possible bitwise AND for $$$q$$$ different values of $$$k$$$. Note that queries are independent.

Input: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^6$$$) — the size of the array and the number of queries.The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.Next $$$q$$$ lines describe the queries. The $$$i$$$-th line contains one integer $$$k_i$$$ ($$$0 \le k_i \le 10^{18}$$$) — the number of operations that can be done in the $$$i$$$-th query.

Output: For each query, print one integer — the maximum bitwise AND that array $$$a$$$ can have after at most $$$k_i$$$ operations.

Note: In the first test case, in the first query, we add $$$1$$$ in the first and last elements of the array. Thus, the array becomes $$$[2,3,7,6]$$$ with bitwise AND equal to $$$2$$$.In the second test case, in the first query, we add $$$1$$$ in the first element, $$$5$$$ in the second, and $$$3$$$ in the third and now all the elements are equal to $$$5$$$.

Sample Inputs:
4 2
1 3 7 5
2
10

3 5
4 0 2
9
8
17
1
3

1 2
10
5
2318381298321

Sample Outputs:
2
6

5
4
7
0
1

15
2318381298331

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        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.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

def main():
    (n, q) = MII()
    nums = LII()
    dp = [0] * (1 << 20)
    for num in nums:
        last = -1
        cur = 0
        for j in range(19, -1, -1):
            if num >> j & 1:
                cur += 1 << j
                x = (1 << j) - (num & (1 << j) - 1)
                dp[cur] += x
                if last != -1:
                    dp[last] -= x
                last = cur
    for j in range(19, -1, -1):
        for i in range(1 << 20):
            if i >> j & 1:
                dp[i - (1 << j)] += dp[i]
    dp[0] = 0
    for i in range(1 << 20):
        if i < len(dp) - 1:
            dp[i + 1] += dp[i]
        dp[i] = n * i - dp[i]
    for j in range((1 << 20) - 2, -1, -1):
        dp[j] = min(dp[j], dp[j + 1])
    v = sum(((1 << 20) - x for x in nums))
    for _ in range(q):
        x = II()
        if x >= v:
            print((1 << 20) + (x - v) // n)
        else:
            print(bisect.bisect_right(dp, x) - 1)
    return
t = 1
for _ in range(t):
    main()

Solution (Python):
import sys
import time
ts = time.time()
(n, q) = map(int, input().split())
a = list(map(int, input().split()))
qq = sys.stdin.readlines()
kmax = 20
u = [0] * (1 << kmax)
for ai in a:
    u[ai] += 1
v0 = [None] * (1 << kmax)
v1 = [0] * (1 << kmax)
for k in range(kmax):
    k2 = 1 << k
    (v0, v1) = (v1, v0)
    for i0 in range(0, 1 << kmax, 2 * k2):
        i1 = i0 + k2
        for j in range(k2):
            v1[i0 + j] = v0[i0 + j] + v0[i1 + j]
        c = sum(u[i0:i0 + k2])
        s = sum((u[i0 + x] * (k2 - x) for x in range(k2)))
        for j in range(k2):
            v1[i1 + j] = s + j * c + v0[i1 + j]
qq = sorted(((int(qq[i]), i) for i in range(q)))
ans = [None] * q
x = (1 << kmax) - 1
for (qk, i) in qq[::-1]:
    if qk >= v1[-1]:
        ans[i] = (1 << kmax) - 1 + (qk - v1[-1]) // n
        continue
    while v1[x] > qk:
        x -= 1
    ans[i] = x
for a in ans:
    print(a)

Solution (Python):
import sys
import time
ts = time.time()
(n, q) = map(int, input().split())
a = list(map(int, input().split()))
qq = sys.stdin.readlines()
kmax = 20
u = [0] * (1 << kmax)
for ai in a:
    u[ai] += 1
v0 = [None] * (1 << kmax)
v1 = [0] * (1 << kmax)
for k in range(kmax):
    k2 = 1 << k
    (v0, v1) = (v1, v0)
    for i0 in range(0, 1 << kmax, 2 * k2):
        i1 = i0 + k2
        for j in range(k2):
            v1[i0 + j] = v0[i0 + j] + v0[i1 + j]
        c = sum(u[i0:i0 + k2])
        s = sum((u[i0 + x] * (k2 - x) for x in range(k2)))
        for j in range(k2):
            v1[i1 + j] = s + j * c + v0[i1 + j]
qq = sorted(((int(qq[i]), i) for i in range(q)))
ans = [None] * q
x = (1 << kmax) - 1
for (qk, i) in qq[::-1]:
    if qk >= v1[-1]:
        ans[i] = (1 << kmax) - 1 + (qk - v1[-1]) // n
        continue
    while v1[x] > qk:
        x -= 1
    ans[i] = x
for a in ans:
    print(a)