Periodic RMQ Problem (Codeforces 803G)
Tags: Others, data structures

You are given an array a consisting of positive integers and q queries to this array. There are two types of queries:   1 l r x — for each index i such that l ≤ i ≤ r set ai = x.  2 l r — find the minimum among such ai that l ≤ i ≤ r. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is n·k).

Input: The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 104).The second line contains n integers — elements of the array b (1 ≤ bi ≤ 109).The third line contains one integer q (1 ≤ q ≤ 105).Then q lines follow, each representing a query. Each query is given either as 1 l r x — set all elements in the segment from l till r (including borders) to x (1 ≤ l ≤ r ≤ n·k, 1 ≤ x ≤ 109) or as 2 l r — find the minimum among all elements in the segment from l till r (1 ≤ l ≤ r ≤ n·k).

Output: For each query of type 2 print the answer to this query — the minimum on the corresponding segment.


Sample Inputs:
3 1
1 2 3
3
2 1 3
1 1 2 4
2 1 3

3 2
1 2 3
5
2 4 4
1 4 4 5
2 4 4
1 1 6 1
2 6 6

Sample Outputs:
1
3

1
5
1

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

def slide_min(n, k, a):
    ans = []
    s = deque()
    for i in range(n):
        ai = a[i]
        while s:
            if a[s[-1]] >= ai:
                s.pop()
            else:
                break
        s.append(i)
        while s:
            if s[0] + k <= i:
                s.popleft()
            else:
                break
        if (i + 1) // k:
            ans.append(a[s[0]])
    return ans

def make_sparse_table(a):
    table = []
    (s, l) = (a, 1)
    table.append(s)
    while 2 * l <= len(a):
        s = slide_min(len(s), l + 1, s)
        table.append(s)
        l *= 2
    return table

def get_min(l, r):
    d = len(bin(r - l + 1)) - 3
    ans = min(table[d][l], table[d][r - pow2[d] + 1])
    return ans

def make_tree(n):
    n0 = 1
    while n0 < n:
        n0 *= 2
    tree = [inf] * (2 * n0)
    lazy = [inf] * (2 * n0)
    return (tree, lazy)

def eval(s, t, a):
    b = []
    (u, v) = ([0, len(tree) // 2 - 1], [0, len(tree) // 2 - 1])
    (x, y) = (1, 1)
    if lazy[x] ^ inf:
        tree[x] = lazy[x]
    while u[0] ^ u[1]:
        (lx, ly) = (lazy[x], lazy[y])
        if not x in a:
            b.append(x)
        if lx ^ inf:
            lazy[x] = inf
            (lazy[2 * x], lazy[2 * x + 1]) = (lx, lx)
            (tree[2 * x], tree[2 * x + 1]) = (lx, lx)
        if not y in a:
            b.append(y)
        if ly ^ inf:
            lazy[y] = inf
            (lazy[2 * y], lazy[2 * y + 1]) = (ly, ly)
            (tree[2 * y], tree[2 * y + 1]) = (ly, ly)
        (u0, u1) = u
        if u0 <= s <= (u0 + u1) // 2:
            u1 = (u0 + u1) // 2
            x = 2 * x
        else:
            u0 = (u0 + u1) // 2 + 1
            x = 2 * x + 1
        u = [u0, u1]
        (v0, v1) = v
        if v0 <= t <= (v0 + v1) // 2:
            v1 = (v0 + v1) // 2
            y = 2 * y
        else:
            v0 = (v0 + v1) // 2 + 1
            y = 2 * y + 1
        v = [v0, v1]
    (tree[x], tree[y]) = (lazy[x], lazy[y])
    return b

def update(s, t, x):
    (s0, t0) = (s, t)
    s += len(tree) // 2
    t += len(tree) // 2
    a = set()
    while s <= t:
        if s % 2 == 0:
            s //= 2
        else:
            a.add(s)
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            a.add(t)
            t = (t - 1) // 2
    b = eval(s0, t0, a)
    for i in a:
        (tree[i], lazy[i]) = (x, x)
    while b:
        i = b.pop()
        tree[i] = min(tree[2 * i], tree[2 * i + 1])
    return

def get_ans(s, t):
    (s0, t0) = (s, t)
    s += len(tree) // 2
    t += len(tree) // 2
    a = set()
    while s <= t:
        if s % 2 == 0:
            s //= 2
        else:
            a.add(s)
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            a.add(t)
            t = (t - 1) // 2
    eval(s0, t0, a)
    ans = inf
    for i in a:
        ans = min(ans, tree[i])
    return ans
(n, k) = map(int, input().split())
b = list(map(int, input().split()))
table = make_sparse_table(b)
pow2 = [1]
for _ in range(20):
    pow2.append(2 * pow2[-1])
x = set()
qs = []
q = int(input())
for _ in range(q):
    t = list(map(int, input().split()))
    x.add(t[1])
    x.add(t[2])
    qs.append(t)
x = list(x)
x.sort()
mi = min(b)
l = 1
a = []
d = dict()
for y in x:
    r = y - 1
    if l <= r:
        if l + n <= r:
            m0 = mi
        else:
            (l0, r0) = ((l - 1) % n, (r - 1) % n)
            if l0 <= r0:
                m0 = get_min(l0, r0)
            else:
                m0 = min(get_min(0, r0), get_min(l0, n - 1))
        a.append(m0)
    d[y] = len(a)
    a.append(b[(y - 1) % n])
    l = y + 1
inf = pow(10, 9) + 7
n = len(a)
(tree, lazy) = make_tree(n)
for i in range(n):
    update(i, i, a[i])
for t in qs:
    if t[0] == 1:
        (ty, l, r, x) = t
        update(d[l], d[r], x)
    else:
        (ty, l, r) = t
        ans = get_ans(d[l], d[r])
        print(ans)

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()
        inf = float('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 math
        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 SparseTable:

    def __init__(self, data, merge_method):
        self.note = [0] * (len(data) + 1)
        self.merge_method = merge_method
        (l, r, v) = (1, 2, 0)
        while True:
            for i in range(l, r):
                if i >= len(self.note):
                    break
                self.note[i] = v
            else:
                l *= 2
                r *= 2
                v += 1
                continue
            break
        self.ST = [[0] * len(data) for _ in range(self.note[-1] + 1)]
        self.ST[0] = data
        for i in range(1, len(self.ST)):
            for j in range(len(data) - (1 << i) + 1):
                self.ST[i][j] = merge_method(self.ST[i - 1][j], self.ST[i - 1][j + (1 << i - 1)])

    def query(self, l, r):
        pos = self.note[r - l + 1]
        return self.merge_method(self.ST[pos][l], self.ST[pos][r - (1 << pos) + 1])

class LazySegTree:

    def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, mapping: typing.Callable[[typing.Any, typing.Any], typing.Any], composition: typing.Callable[[typing.Any, typing.Any], typing.Any], id_: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
        self._op = op
        self._e = e
        self._mapping = mapping
        self._composition = composition
        self._id = id_
        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)
        self._lz = [self._id] * self._size
        for i in range(self._n):
            self._d[self._size + i] = v[i]
        for i in range(self._size - 1, 0, -1):
            self._update(i)

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

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

    def prod(self, left: int, right: int) -> typing.Any:
        assert 0 <= left <= right <= self._n
        if left == right:
            return self._e
        left += self._size
        right += self._size
        for i in range(self._log, 0, -1):
            if left >> i << i != left:
                self._push(left >> i)
            if right >> i << i != right:
                self._push(right >> i)
        sml = self._e
        smr = self._e
        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 all_prod(self) -> typing.Any:
        return self._d[1]

    def apply(self, left: int, right: typing.Optional[int]=None, f: typing.Optional[typing.Any]=None) -> None:
        assert f is not None
        if right is None:
            p = left
            assert 0 <= left < self._n
            p += self._size
            for i in range(self._log, 0, -1):
                self._push(p >> i)
            self._d[p] = self._mapping(f, self._d[p])
            for i in range(1, self._log + 1):
                self._update(p >> i)
        else:
            assert 0 <= left <= right <= self._n
            if left == right:
                return
            left += self._size
            right += self._size
            for i in range(self._log, 0, -1):
                if left >> i << i != left:
                    self._push(left >> i)
                if right >> i << i != right:
                    self._push(right - 1 >> i)
            l2 = left
            r2 = right
            while left < right:
                if left & 1:
                    self._all_apply(left, f)
                    left += 1
                if right & 1:
                    right -= 1
                    self._all_apply(right, f)
                left >>= 1
                right >>= 1
            left = l2
            right = r2
            for i in range(1, self._log + 1):
                if left >> i << i != left:
                    self._update(left >> i)
                if right >> i << i != right:
                    self._update(right - 1 >> i)

    def max_right(self, left: int, g: typing.Callable[[typing.Any], bool]) -> int:
        assert 0 <= left <= self._n
        assert g(self._e)
        if left == self._n:
            return self._n
        left += self._size
        for i in range(self._log, 0, -1):
            self._push(left >> i)
        sm = self._e
        first = True
        while first or left & -left != left:
            first = False
            while left % 2 == 0:
                left >>= 1
            if not g(self._op(sm, self._d[left])):
                while left < self._size:
                    self._push(left)
                    left *= 2
                    if g(self._op(sm, self._d[left])):
                        sm = self._op(sm, self._d[left])
                        left += 1
                return left - self._size
            sm = self._op(sm, self._d[left])
            left += 1
        return self._n

    def min_left(self, right: int, g: typing.Any) -> int:
        assert 0 <= right <= self._n
        assert g(self._e)
        if right == 0:
            return 0
        right += self._size
        for i in range(self._log, 0, -1):
            self._push(right - 1 >> i)
        sm = self._e
        first = True
        while first or right & -right != right:
            first = False
            right -= 1
            while right > 1 and right % 2:
                right >>= 1
            if not g(self._op(self._d[right], sm)):
                while right < self._size:
                    self._push(right)
                    right = 2 * right + 1
                    if g(self._op(self._d[right], sm)):
                        sm = self._op(self._d[right], sm)
                        right -= 1
                return right + 1 - self._size
            sm = self._op(self._d[right], sm)
        return 0

    def _update(self, k: int) -> None:
        self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])

    def _all_apply(self, k: int, f: typing.Any) -> None:
        self._d[k] = self._mapping(f, self._d[k])
        if k < self._size:
            self._lz[k] = self._composition(f, self._lz[k])

    def _push(self, k: int) -> None:
        self._all_apply(2 * k, self._lz[k])
        self._all_apply(2 * k + 1, self._lz[k])
        self._lz[k] = self._id

def main():
    (n, k) = MII()
    nums = LII()
    q = II()
    queries = []
    seps = []
    for _ in range(q):
        query = LGMI()
        if query[0]:
            (l, r) = (query[1], query[2])
            x = -1
        else:
            (l, r, x) = (query[1], query[2], query[3] + 1)
        queries.append((l, r + 1, x))
        seps.append(l)
        seps.append(r + 1)
    seps = sorted(set(sorted(seps)))
    st = SparseTable(nums, lambda x, y: x if x < y else y)
    mi = min(nums)
    tmp = []
    for i in range(len(seps) - 1):
        (l, r) = (seps[i], seps[i + 1])
        r -= 1
        if r - l >= n:
            tmp.append(mi)
        else:
            l %= n
            r %= n
            tmp.append(st.query(l, r) if l <= r else min(st.query(l, n - 1), st.query(0, r)))
    d = {v: i for (i, v) in enumerate(seps)}

    def f(x, y):
        return x if x != -1 else y
    lazy_seg = LazySegTree(lambda x, y: x if x < y else y, 10 ** 9, f, f, -1, tmp)
    for (l, r, x) in queries:
        if x != -1:
            lazy_seg.apply(d[l], d[r], x)
        else:
            print(lazy_seg.prod(d[l], d[r]))
    return
t = 1
for _ in range(t):
    main()

Solution (Python):
class segtree:

    def __init__(self, init, func, ide):
        self.n = len(init)
        self.func = func
        self.ide = ide
        self.size = 1 << (self.n - 1).bit_length()
        self.tree = [self.ide for i in range(2 * self.size)]
        for i in range(self.n):
            self.tree[self.size + i] = init[i]
        for i in range(self.size - 1, 0, -1):
            self.tree[i] = self.func(self.tree[2 * i], self.tree[2 * i | 1])

    def update(self, k, x):
        k += self.size
        self.tree[k] = x
        k >>= 1
        while k:
            self.tree[k] = self.func(self.tree[2 * k], self.tree[k * 2 | 1])
            k >>= 1

    def get(self, i):
        return self.tree[i + self.size]

    def query(self, l, r):
        l += self.size
        r += self.size
        l_res = self.ide
        r_res = self.ide
        while l < r:
            if l & 1:
                l_res = self.func(l_res, self.tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_res = self.func(self.tree[r], r_res)
            l >>= 1
            r >>= 1
        return self.func(l_res, r_res)

    def debug(self, s=10):
        print([self.get(i) for i in range(min(self.n, s))])

class lazy_segtree:

    def update(self, k):
        self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])

    def all_apply(self, k, f):
        self.d[k] = self.mapping(f, self.d[k])
        if k < self.size:
            self.lz[k] = self.composition(f, self.lz[k])

    def push(self, k):
        self.all_apply(2 * k, self.lz[k])
        self.all_apply(2 * k + 1, self.lz[k])
        self.lz[k] = self.identity

    def __init__(self, V, OP, E, MAPPING, COMPOSITION, ID):
        self.n = len(V)
        self.log = (self.n - 1).bit_length()
        self.size = 1 << self.log
        self.d = [E for i in range(2 * self.size)]
        self.lz = [ID for i in range(self.size)]
        self.e = E
        self.op = OP
        self.mapping = MAPPING
        self.composition = COMPOSITION
        self.identity = ID
        for i in range(self.n):
            self.d[self.size + i] = V[i]
        for i in range(self.size - 1, 0, -1):
            self.update(i)

    def set(self, p, x):
        assert 0 <= p and p < self.n
        p += self.size
        for i in range(self.log, 0, -1):
            self.push(p >> i)
        self.d[p] = x
        for i in range(1, self.log + 1):
            self.update(p >> i)

    def get(self, p):
        assert 0 <= p and p < self.n
        p += self.size
        for i in range(self.log, 0, -1):
            self.push(p >> i)
        return self.d[p]

    def prod(self, l, r):
        assert 0 <= l and l <= r and (r <= self.n)
        if l == r:
            return self.e
        l += self.size
        r += self.size
        for i in range(self.log, 0, -1):
            if l >> i << i != l:
                self.push(l >> i)
            if r >> i << i != r:
                self.push(r >> i)
        (sml, smr) = (self.e, self.e)
        while l < r:
            if l & 1:
                sml = self.op(sml, self.d[l])
                l += 1
            if r & 1:
                r -= 1
                smr = self.op(self.d[r], smr)
            l >>= 1
            r >>= 1
        return self.op(sml, smr)

    def all_prod(self):
        return self.d[1]

    def apply_point(self, p, f):
        assert 0 <= p and p < self.n
        p += self.size
        for i in range(self.log, 0, -1):
            self.push(p >> i)
        self.d[p] = self.mapping(f, self.d[p])
        for i in range(1, self.log + 1):
            self.update(p >> i)

    def apply(self, l, r, f):
        assert 0 <= l and l <= r and (r <= self.n)
        if l == r:
            return
        l += self.size
        r += self.size
        for i in range(self.log, 0, -1):
            if l >> i << i != l:
                self.push(l >> i)
            if r >> i << i != r:
                self.push(r - 1 >> i)
        (l2, r2) = (l, r)
        while l < r:
            if l & 1:
                self.all_apply(l, f)
                l += 1
            if r & 1:
                r -= 1
                self.all_apply(r, f)
            l >>= 1
            r >>= 1
        (l, r) = (l2, r2)
        for i in range(1, self.log + 1):
            if l >> i << i != l:
                self.update(l >> i)
            if r >> i << i != r:
                self.update(r - 1 >> i)

    def max_right(self, l, g):
        assert 0 <= l and l <= self.n
        assert g(self.e)
        if l == self.n:
            return self.n
        l += self.size
        for i in range(self.log, 0, -1):
            self.push(l >> i)
        sm = self.e
        while 1:
            while l % 2 == 0:
                l >>= 1
            if not g(self.op(sm, self.d[l])):
                while l < self.size:
                    self.push(l)
                    l = 2 * l
                    if g(self.op(sm, self.d[l])):
                        sm = self.op(sm, self.d[l])
                        l += 1
                return l - self.size
            sm = self.op(sm, self.d[l])
            l += 1
            if l & -l == l:
                break
        return self.n

    def min_left(self, r, g):
        assert 0 <= r and r <= self.n
        assert g(self.e)
        if r == 0:
            return 0
        r += self.size
        for i in range(self.log, 0, -1):
            self.push(r - 1 >> i)
        sm = self.e
        while 1:
            r -= 1
            while r > 1 and r % 2:
                r >>= 1
            if not g(self.op(self.d[r], sm)):
                while r < self.size:
                    self.push(r)
                    r = 2 * r + 1
                    if g(self.op(self.d[r], sm)):
                        sm = self.op(self.d[r], sm)
                        r -= 1
                return r + 1 - self.size
            sm = self.op(self.d[r], sm)
            if r & -r == r:
                break
        return 0
from sys import stdin
input = lambda : stdin.readline()[:-1]
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
s = set()
query = []
q = int(input())
for _ in range(q):
    x = list(map(int, input().split()))
    if len(x) == 3:
        x += [-1]
    x[1] -= 1
    x[2] -= 1
    s.add(x[1])
    if x[1] > 0:
        s.add(x[1] - 1)
    s.add(x[2])
    if x[2] < n * k - 1:
        s.add(x[2] + 1)
    query.append(x)
mn = min(a)
seg = segtree(a + a, min, 10 ** 9 + 10)
s = sorted(list(s))
m = len(s)
res = []
d = {}
tmp = 0
for i in range(m):
    if i != 0 and s[i] - s[i - 1] > 1:
        l = s[i - 1] + 1
        r = s[i] - 1
        if r - l >= n - 1:
            res.append(mn)
            tmp += 1
        else:
            l %= n
            r %= n
            if l > r:
                r += n
            res.append(seg.query(l, r + 1))
            tmp += 1
    d[s[i]] = tmp
    res.append(a[s[i] % n])
    tmp += 1

def operate(a, b):
    return min(a, b)
id = 10 ** 9 + 10
e = 10 ** 9 + 10

def mapping(f, x):
    if f == id:
        return x
    return f

def compposition(f, g):
    if f == id:
        return g
    return f
seg = lazy_segtree(res, operate, e, mapping, compposition, id)
ans = []
for (t, l, r, x) in query:
    l = d[l]
    r = d[r]
    if t == 1:
        seg.apply(l, r + 1, x)
    else:
        ans.append(seg.prod(l, r + 1))
print(*ans, sep='\n')