The Wu (Codeforces 1017D)
Tags: Others, bitmasks

Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.This "personal treasure" is a multiset $$$S$$$ of $$$m$$$ "01-strings".A "01-string" is a string that contains $$$n$$$ characters "0" and "1". For example, if $$$n=4$$$, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are $$$5$$$ characters, not $$$4$$$) and "zero" (unallowed characters) are not.Note that the multiset $$$S$$$ can contain equal elements.Frequently, Mr. Kasoura will provide a "01-string" $$$t$$$ and ask Childan how many strings $$$s$$$ are in the multiset $$$S$$$ such that the "Wu" value of the pair $$$(s, t)$$$ is not greater than $$$k$$$. Mrs. Kasoura and Mr. Kasoura think that if $$$s_i = t_i$$$ ($$$1\leq i\leq n$$$) then the "Wu" value of the character pair equals to $$$w_i$$$, otherwise $$$0$$$. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to $$$n$$$.For example, if $$$w=[4, 5, 3, 6]$$$, "Wu" of ("1001", "1100") is $$$7$$$ because these strings have equal characters only on the first and third positions, so $$$w_1+w_3=4+3=7$$$.You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset $$$S$$$ such that the "Wu" value of the pair is not greater than $$$k$$$.

Input: The first line contains three integers $$$n$$$, $$$m$$$, and $$$q$$$ ($$$1\leq n\leq 12$$$, $$$1\leq q, m\leq 5\cdot 10^5$$$) — the length of the "01-strings", the size of the multiset $$$S$$$, and the number of queries.The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 100$$$) — the value of the $$$i$$$-th caracter.Each of the next $$$m$$$ lines contains the "01-string" $$$s$$$ of length $$$n$$$ — the string in the multiset $$$S$$$.Each of the next $$$q$$$ lines contains the "01-string" $$$t$$$ of length $$$n$$$ and integer $$$k$$$ ($$$0\leq k\leq 100$$$) — the query.

Output: For each query, print the answer for this query.

Note: In the first example, we can get:"Wu" of ("01", "00") is $$$40$$$."Wu" of ("10", "00") is $$$20$$$."Wu" of ("11", "00") is $$$0$$$."Wu" of ("01", "11") is $$$20$$$."Wu" of ("10", "11") is $$$40$$$."Wu" of ("11", "11") is $$$60$$$.In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than $$$20$$$.In the second query, all strings satisfy the condition.In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is $$$2$$$, not $$$1$$$.In the fourth query, since $$$k$$$ was increased, pair ("10", "11") satisfies the condition too.In the fifth query, since $$$k$$$ was increased, pair ("11", "11") satisfies the condition too.

Sample Inputs:
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60

1 2 4
100
0
1
0 0
0 100
1 0
1 100

Sample Outputs:
2
4
2
3
4

1
2
1
2

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

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, 8192))
            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, 8192))
            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')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
get_bit = lambda x, i: x >> i & 1
(n, m, q) = inp(int)
(w, ma) = (inp(int), 1 << n)
cost = [sum([(get_bit(i, j) ^ 1) * w[n - j - 1] for j in range(n)]) for i in range(ma)]
(wu, mem) = ([[0] * 101 for _ in range(ma)], [0] * ma)
for i in range(m):
    x = int(input(), 2)
    mem[x] += 1
for i in range(ma):
    for j in range(ma):
        val = i ^ j
        if cost[val] < 101:
            wu[i][cost[val]] += mem[j]
    for j in range(1, 101):
        wu[i][j] += wu[i][j - 1]
for _ in range(q):
    (s, k) = inp(str)
    (s, k) = (int(s, 2), int(k))
    print(wu[s][k])

Solution (Python):
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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 SegmentTree:

    def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
        """"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()
        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size
        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

    def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
        """"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()
        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size
        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print('Invalid argument to calculate n!')
            print('n must be non-negative value. But the argument was ' + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print('Invalid argument to calculate n^(-1)')
            print('n must be non-negative value. But the argument was ' + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print('Invalid argument to calculate (n^(-1))!')
            print('n must be non-negative value. But the argument was ' + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:

    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(200001)]
pp = [0] * 200001

def SieveOfEratosthenes(n=200000):
    p = 2
    while p * p <= n:
        if prime[p] == True:
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
(n, m, q) = map(int, input().split())
c = sz = 1 << n
(costs, cnt) = ([0] * sz, [0] * sz)
for w in map(int, input().split()):
    c //= 2
    for i in range(c, sz, c * 2):
        for j in range(i, i + c):
            costs[j] += w
for (i, c) in enumerate(costs):
    if c > 101:
        costs[i] = 101
costs.reverse()
l = sys.stdin.read().splitlines()
for s in l[:m]:
    cnt[int(s, 2)] += 1
del l[:m]
cache = []
for i in range(sz):
    row = [0] * 102
    cache.append(row)
    for (j, c) in enumerate(cnt):
        row[costs[i ^ j]] += c
    a = 0
    for (j, b) in enumerate(row):
        a += b
        row[j] = a
for (i, s) in enumerate(l):
    row = s.split()
    l[i] = str(cache[int(row[0], 2)][int(row[1])])
print('\n'.join(l))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m, q) = map(int, input().split())
w = list(map(int, input().split()))
w.reverse()
pow2 = [1]
for _ in range(n):
    pow2.append(2 * pow2[-1])
cnt = [0] * pow2[n]
for _ in range(m):
    s0 = input().rstrip().decode()
    cnt[int(s0, 2)] += 1
x = [[] for _ in range(pow2[n])]
for i in range(q):
    (t0, k) = input().rstrip().decode().split()
    x[int(t0, 2)].append((int(k), i))
ans = [0] * q
c = [0] * pow2[n]
for i in range(pow2[n]):
    for j in range(n):
        if not i & pow2[j]:
            c[i] += w[j]
g = []
for i in range(n):
    g = g + [i] + g
g.append(0)
i = 0
l = 105
for g0 in g:
    if x[i]:
        u = [0] * l
        for (j, k) in zip(c, cnt):
            if j < l:
                u[j] += k
        for j in range(1, l):
            u[j] += u[j - 1]
        for (k, j) in x[i]:
            ans[j] = u[k]
    y = w[g0]
    d = 1 if not i & pow2[g0] else -1
    for j in range(pow2[n]):
        c[j] += d * y if j & pow2[g0] else -d * y
    i ^= pow2[g0]
sys.stdout.write('\n'.join(map(str, ans)))