Multidimensional Queries (Codeforces 1093G)
Tags: Others, bitmasks

You are given an array $$$a$$$ of $$$n$$$ points in $$$k$$$-dimensional space. Let the distance between two points $$$a_x$$$ and $$$a_y$$$ be $$$\sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|$$$ (it is also known as Manhattan distance).You have to process $$$q$$$ queries of the following two types: $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ — set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ — find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \le i, j \le r$$$.

Input: The first line contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le 5$$$) — the number of elements in $$$a$$$ and the number of dimensions of the space, respectively.Then $$$n$$$ lines follow, each containing $$$k$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, k}$$$ ($$$-10^6 \le a_{i, j} \le 10^6$$$) — the coordinates of $$$i$$$-th point.The next line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries.Then $$$q$$$ lines follow, each denoting a query. There are two types of queries: $$$1$$$ $$$i$$$ $$$b_1$$$ $$$b_2$$$ ... $$$b_k$$$ ($$$1 \le i \le n$$$, $$$-10^6 \le b_j \le 10^6$$$) — set $$$i$$$-th element of $$$a$$$ to the point $$$(b_1, b_2, \dots, b_k)$$$; $$$2$$$ $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$) — find the maximum distance between two points $$$a_i$$$ and $$$a_j$$$, where $$$l \le i, j \le r$$$.There is at least one query of the second type.

Output: Print the answer for each query of the second type.


Sample Inputs:
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5

Sample Outputs:
8
4
4
12
10

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

def segment_tree(n, a):
    i = 2
    while True:
        if i >= n * 2:
            tree = [-inf] * i
            break
        else:
            i *= 2
    l = len(tree) // 2
    for i in range(l, l + len(a)):
        tree[i] = a[i - l]
    for i in range(l - 1, 0, -1):
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
    return tree

def update(i, x, tree):
    i += len(tree) // 2
    tree[i] = x
    i //= 2
    while True:
        if i == 0:
            break
        tree[i] = max(tree[2 * i], tree[2 * i + 1])
        i //= 2
    return

def get_max(s, t, tree):
    s += len(tree) // 2
    t += len(tree) // 2
    ans = -inf
    while s <= t:
        if s % 2 == 0:
            s //= 2
        else:
            ans = max(ans, tree[s])
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            ans = max(ans, tree[t])
            t = (t - 1) // 2
    return ans
(n, k) = map(int, input().split())
inf = pow(10, 7) + 1
pow2 = [1]
for _ in range(k):
    pow2.append(2 * pow2[-1])
m = pow2[k]
m0 = m - 1
x = [[-inf] for _ in range(m)]
for _ in range(n):
    a = list(map(int, input().split()))
    for i in range(m):
        c = 0
        for j in range(k):
            pj = pow2[j]
            if pj & i:
                c += a[j]
            else:
                c -= a[j]
        x[i].append(c)
s = []
for x0 in x:
    s.append(segment_tree(n + 1, x0))
q = int(input())
ans = []
for _ in range(q):
    t = list(map(int, input().split()))
    if t[0] == 1:
        l = t[1]
        b = t[2:]
        for i in range(m):
            c = 0
            for j in range(k):
                pj = pow2[j]
                if pj & i:
                    c += b[j]
                else:
                    c -= b[j]
            update(l, c, s[i])
    else:
        (l, r) = (t[1], t[2])
        ans0 = -inf
        for i in range(m // 2):
            ans0 = max(ans0, get_max(l, r, s[i]) + get_max(l, r, s[i ^ m0]))
        ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 0)
(dfs, hashing, read_from_file) = (1, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().rstrip()
        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='')

class SegTree:

    def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
        self._op = op
        self._e = e
        if isinstance(v, int):
            v = [e] * v
        self._n = len(v)
        self._log = (self._n - 1).bit_length()
        self._size = 1 << self._log
        self._d = [e] * (2 * self._size)

    def build(self):
        for i in range(self._size - 1, 0, -1):
            self._update(i)

    def set1(self, p: int, x: typing.Any) -> None:
        assert 0 <= p < self._n
        p += self._size
        self._d[p] = x

    def set(self, p: int, x: typing.Any) -> None:
        assert 0 <= p < self._n
        p += self._size
        self._d[p] = x
        for i in range(1, self._log + 1):
            self._update(p >> i)

    def prod(self, left: int, right: int) -> typing.Any:
        assert 0 <= left <= right <= self._n
        sml = self._e
        smr = self._e
        left += self._size
        right += self._size
        while left < right:
            if left & 1:
                sml = self._op(sml, self._d[left])
                left += 1
            if right & 1:
                right -= 1
                smr = self._op(self._d[right], smr)
            left >>= 1
            right >>= 1
        return self._op(sml, smr)

    def _update(self, k: int) -> None:
        self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])
inf = 10 ** 9
(n, k) = MII()
minimums = [SegTree(min, inf, n) for _ in range(1 << k)]
for idx in range(n):
    nums = LII()
    note = [0]
    for i in range(k):
        for j in range(len(note)):
            note.append(note[j] - 2 * nums[i])
    tot = sum(nums)
    for i in range(1 << k):
        minimums[i].set1(idx, tot + note[i])
for i in range(1 << k):
    minimums[i].build()
outs = []
tot_msk = (1 << k) - 1
q = II()
for _ in range(q):
    query = LII()
    if query[0] == 1:
        idx = query[1] - 1
        nums = query[2:]
        note = [0]
        for i in range(k):
            for j in range(len(note)):
                note.append(note[j] - 2 * nums[i])
        tot = sum(nums)
        for i in range(1 << k):
            minimums[i].set(idx, tot + note[i])
    else:
        (l, r) = query[1:]
        l -= 1
        outs.append(max((abs(minimums[tot_msk - i].prod(l, r) + minimums[i].prod(l, r)) for i in range(1 << k - 1))))
print('\n'.join(map(str, outs)))

Solution (Python):
import sys
input = lambda : sys.stdin.readline()[:-1]
ni = lambda : int(input())
na = lambda : list(map(int, input().split()))
yes = lambda : print('yes')
Yes = lambda : print('Yes')
YES = lambda : print('YES')
no = lambda : print('no')
No = lambda : print('No')
NO = lambda : print('NO')
inf = 10 ** 18

class SegmentTree:

    def __init__(self, size, a, f=lambda x, y: min(x, y), default=inf):
        self.size = 2 ** (size - 1).bit_length()
        self.default = default
        self.dat = [default] * (self.size * 2)
        self.f = f
        for i in range(size):
            self.dat[i + self.size] = a[i]
        for i in range(self.size - 1, 0, -1):
            self.dat[i] = self.f(self.dat[i * 2], self.dat[i * 2 + 1])

    def update(self, i, x):
        i += self.size
        self.dat[i] = x
        while i > 0:
            i >>= 1
            self.dat[i] = self.f(self.dat[i * 2], self.dat[i * 2 + 1])

    def updatef(self, i, x):
        i += self.size
        self.dat[i] = self.f(self.dat[i], x)
        while i > 0:
            i >>= 1
            self.dat[i] = self.f(self.dat[i * 2], self.dat[i * 2 + 1])

    def query(self, l, r):
        l += self.size
        r += self.size
        (lres, rres) = (self.default, self.default)
        while l < r:
            if l & 1:
                lres = self.f(lres, self.dat[l])
                l += 1
            if r & 1:
                r -= 1
                rres = self.f(self.dat[r], rres)
            l >>= 1
            r >>= 1
        res = self.f(lres, rres)
        return res

    def query2(self):
        s = 1
        while s < self.size:
            if self.dat[s * 2] > self.dat[s * 2 + 1]:
                s = s * 2
            else:
                s = s * 2 + 1
        return s - self.size

def f(a):
    return [a[0] + a[1] + a[2] + a[3] + a[4], a[0] + a[1] + a[2] + a[3] - a[4], a[0] + a[1] + a[2] - a[3] + a[4], a[0] + a[1] + a[2] - a[3] - a[4], a[0] + a[1] - a[2] + a[3] + a[4], a[0] + a[1] - a[2] + a[3] - a[4], a[0] + a[1] - a[2] - a[3] + a[4], a[0] + a[1] - a[2] - a[3] - a[4], a[0] - a[1] + a[2] + a[3] + a[4], a[0] - a[1] + a[2] + a[3] - a[4], a[0] - a[1] + a[2] - a[3] + a[4], a[0] - a[1] + a[2] - a[3] - a[4], a[0] - a[1] - a[2] + a[3] + a[4], a[0] - a[1] - a[2] + a[3] - a[4], a[0] - a[1] - a[2] - a[3] + a[4], a[0] - a[1] - a[2] - a[3] - a[4]]
(n, k) = na()
a = [na() + [0] * (5 - k) for i in range(n)]
a = list(zip(*[f(a[i]) for i in range(n)]))
q = ni()
query = []
ans = [-1] * q
for _ in range(q):
    que = na()
    if que[0] == 1:
        query.append((que[0], que[1], f(que[2:] + [0] * (5 - k))))
    else:
        query.append(que)
for j in range(16):
    r = SegmentTree(n, a[j], max, -10 ** 9)
    l = SegmentTree(n, a[j], min, 10 ** 9)
    for _ in range(q):
        que = query[_]
        if que[0] == 1:
            i = que[1] - 1
            r.update(i, que[2][j])
            l.update(i, que[2][j])
        else:
            (L, R) = que[1:]
            L -= 1
            ans[_] = max(ans[_], r.query(L, R) - l.query(L, R))
for j in ans:
    if j != -1:
        print(j)