Serge and Dining Room (Codeforces 1179C)
Tags: Greedy, graph matchings

Serge came to the school dining room and discovered that there is a big queue here. There are $$$m$$$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.Initially there are $$$n$$$ dishes with costs $$$a_1, a_2, \ldots, a_n$$$. As you already know, there are the queue of $$$m$$$ pupils who have $$$b_1, \ldots, b_m$$$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $$$b_1$$$ togrogs and the last one has $$$b_m$$$ togrogs)Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...)But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining.Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $$$q$$$ queries:  change $$$a_i$$$ to $$$x$$$. It means that the price of the $$$i$$$-th dish becomes $$$x$$$ togrogs.  change $$$b_i$$$ to $$$x$$$. It means that the $$$i$$$-th pupil in the queue has $$$x$$$ togrogs now. Nobody leaves the queue during those queries because a saleswoman is late.After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $$$-1$$$ if there are no dishes at this point, according to rules described above.

Input: The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 300\ 000$$$) — number of dishes and pupils respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^{6}$$$) — elements of array $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_{m}$$$ ($$$1 \leq b_i \leq 10^{6}$$$) — elements of array $$$b$$$. The fourth line conatins integer $$$q$$$ ($$$1 \leq q \leq 300\ 000$$$) — number of queries.Each of the following $$$q$$$ lines contains as follows:   if a query changes price of some dish, it contains $$$1$$$, and two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^{6}$$$), what means $$$a_i$$$ becomes $$$x$$$.  if a query changes number of togrogs of some pupil, it contains $$$2$$$, and two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq m$$$, $$$1 \leq x \leq 10^{6}$$$), what means $$$b_i$$$ becomes $$$x$$$. 

Output: For each of $$$q$$$ queries prints the answer as the statement describes, the answer of the $$$i$$$-th query in the $$$i$$$-th line (the price of the dish which Serge will buy or $$$-1$$$ if nothing remains)

Note: In the first sample after the first query, there is one dish with price $$$100$$$ togrogs and one pupil with one togrog, so Serge will buy the dish with price $$$100$$$ togrogs.In the second sample after the first query, there is one dish with price one togrog and one pupil with $$$100$$$ togrogs, so Serge will get nothing.In the third sample after the first query, nobody can buy the dish with price $$$8$$$, so Serge will take it. After the second query, all dishes will be bought, after the third one the third and fifth pupils will by the first and the second dishes respectively and nobody will by the fourth one.

Sample Inputs:
1 1
1
1
1
1 1 100

1 1
1
1
1
2 1 100

4 6
1 8 2 4
3 3 6 1 5 2
3
1 1 1
2 5 10
1 1 6

Sample Outputs:
100

-1

8
-1
4

Solution (Python):
import sys
from itertools import accumulate

class Lazysegtree:

    def __init__(self, A, intv, initialize=True, segf=min):
        self.N = len(A)
        self.N0 = 2 ** (self.N - 1).bit_length()
        self.intv = intv
        self.segf = segf
        self.lazy = [0] * (2 * self.N0)
        if initialize:
            self.data = [intv] * self.N0 + A + [intv] * (self.N0 - self.N)
            for i in range(self.N0 - 1, 0, -1):
                self.data[i] = self.segf(self.data[2 * i], self.data[2 * i + 1])
        else:
            self.data = [intv] * (2 * self.N0)

    def _ascend(self, k):
        k = k >> 1
        c = k.bit_length()
        for j in range(c):
            idx = k >> j
            self.data[idx] = self.segf(self.data[2 * idx], self.data[2 * idx + 1]) + self.lazy[idx]

    def _descend(self, k):
        k = k >> 1
        idx = 1
        c = k.bit_length()
        for j in range(1, c + 1):
            idx = k >> c - j
            ax = self.lazy[idx]
            if not ax:
                continue
            self.lazy[idx] = 0
            self.data[2 * idx] += ax
            self.data[2 * idx + 1] += ax
            self.lazy[2 * idx] += ax
            self.lazy[2 * idx + 1] += ax

    def query(self, l, r):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        self._descend(Li)
        self._descend(Ri - 1)
        s = self.intv
        while L < R:
            if R & 1:
                R -= 1
                s = self.segf(s, self.data[R])
            if L & 1:
                s = self.segf(s, self.data[L])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def add(self, l, r, x):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        while L < R:
            if R & 1:
                R -= 1
                self.data[R] += x
                self.lazy[R] += x
            if L & 1:
                self.data[L] += x
                self.lazy[L] += x
                L += 1
            L >>= 1
            R >>= 1
        self._ascend(Li)
        self._ascend(Ri - 1)

    def binsearch(self, l, r, check, reverse=False):
        L = l + self.N0
        R = r + self.N0
        Li = L // (L & -L)
        Ri = R // (R & -R)
        self._descend(Li)
        self._descend(Ri - 1)
        (SL, SR) = ([], [])
        while L < R:
            if R & 1:
                R -= 1
                SR.append(R)
            if L & 1:
                SL.append(L)
                L += 1
            L >>= 1
            R >>= 1
        if reverse:
            for idx in SR + SL[::-1]:
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                ax = self.lazy[idx]
                self.lazy[idx] = 0
                self.data[2 * idx] += ax
                self.data[2 * idx + 1] += ax
                self.lazy[2 * idx] += ax
                self.lazy[2 * idx + 1] += ax
                idx = idx << 1
                if check(self.data[idx + 1]):
                    idx += 1
            return idx - self.N0
        else:
            for idx in SL + SR[::-1]:
                if check(self.data[idx]):
                    break
            else:
                return -1
            while idx < self.N0:
                ax = self.lazy[idx]
                self.lazy[idx] = 0
                self.data[2 * idx] += ax
                self.data[2 * idx + 1] += ax
                self.lazy[2 * idx] += ax
                self.lazy[2 * idx + 1] += ax
                idx = idx << 1
                if not check(self.data[idx]):
                    idx += 1
            return idx - self.N0

    def provfunc(self):
        idx = 1
        if self.data[1] >= 0:
            return -1
        while idx < self.N0:
            ax = self.lazy[idx]
            self.lazy[idx] = 0
            self.data[2 * idx] += ax
            self.data[2 * idx + 1] += ax
            self.lazy[2 * idx] += ax
            self.lazy[2 * idx + 1] += ax
            idx = idx << 1
            if self.data[idx + 1] < 0:
                idx += 1
        return idx - self.N0
(N, M) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
table = [0] * (10 ** 6 + 1)
for a in A:
    table[a] -= 1
for b in B:
    table[b] += 1
table = list(accumulate(table[::-1]))[::-1]
T = Lazysegtree(table, 0, True, min)
Q = int(input())
Ans = [None] * Q
for q in range(Q):
    (t, i, x) = map(int, sys.stdin.readline().split())
    i -= 1
    if t == 1:
        T.add(0, x + 1, -1)
        T.add(0, A[i] + 1, 1)
        A[i] = x
    else:
        T.add(0, x + 1, 1)
        T.add(0, B[i] + 1, -1)
        B[i] = x
    Ans[q] = T.provfunc()
print('\n'.join(map(str, Ans)))

Solution (Python):
import sys
input = sys.stdin.buffer.readline

class LazySegmentTree:

    def __init__(self, data, default=0, func=max):
        """"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()
        self._lazy = [0] * (2 * _size)
        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 __len__(self):
        return self._len

    def _push(self, idx):
        """"""
        (q, self._lazy[idx]) = (self._lazy[idx], 0)
        self._lazy[2 * idx] += q
        self._lazy[2 * idx + 1] += q
        self.data[2 * idx] += q
        self.data[2 * idx + 1] += q

    def _update(self, idx):
        """"""
        for i in reversed(range(1, idx.bit_length())):
            self._push(idx >> i)

    def _build(self, idx):
        """"""
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
            idx >>= 1

    def add(self, start, stop, value):
        """"""
        start = start_copy = start + self._size
        stop = stop_copy = stop + self._size
        while start < stop:
            if start & 1:
                self._lazy[start] += value
                self.data[start] += value
                start += 1
            if stop & 1:
                stop -= 1
                self._lazy[stop] += value
                self.data[stop] += value
            start >>= 1
            stop >>= 1
        self._build(start_copy)
        self._build(stop_copy - 1)

    def query(self, start, stop, default=0):
        """"""
        start += self._size
        stop += self._size
        self._update(start)
        self._update(stop - 1)
        res = 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 'LazySegmentTree({0})'.format(self.data)

def find_max(S):
    x1 = S.query(1, 10 ** 6 + 1)
    if x1 <= 0:
        return -1
    s = 1
    e = 10 ** 6 + 1
    while s + 1 < e:
        m = (s + e) // 2
        x1 = S.query(m, 10 ** 6 + 1)
        if x1 > 0:
            (s, e) = (m, e)
        else:
            (s, e) = (s, m)
    return s
S = LazySegmentTree(data=[0 for i in range(10 ** 6 + 2)])
(n, m) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
for ai in A:
    S.add(1, ai + 1, 1)
for bi in B:
    S.add(1, bi + 1, -1)
q = int(input())
Q = []
answer = None
for i in range(q):
    (t, I, X) = [int(x) for x in input().split()]
    if t == 1:
        old_ai = A[I - 1]
        A[I - 1] = X
        new_ai = X
        ''
        if new_ai < old_ai:
            S.add(new_ai + 1, old_ai + 1, -1)
        else:
            S.add(old_ai + 1, new_ai + 1, 1)
    else:
        old_bi = B[I - 1]
        B[I - 1] = X
        new_bi = X
        if new_bi < old_bi:
            S.add(new_bi + 1, old_bi + 1, 1)
        else:
            S.add(old_bi + 1, new_bi + 1, -1)
    if answer is None or not (S.query(answer, 10 ** 6 + 1) > 0 and S.query(answer + 1, 10 ** 6 + 1) <= 0):
        answer = find_max(S)
    sys.stdout.write(str(answer) + '\n')

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 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, m) = MII()
    nums1 = LII()
    nums2 = LII()
    val = 10 ** 6
    values = [0] * (val + 1)
    for num in nums1:
        values[num] += 1
    for num in nums2:
        values[num] -= 1
    for i in range(val, 0, -1):
        values[i - 1] += values[i]
    seg = LazySegTree(lambda x, y: x if x > y else y, -2, add, add, 0, values)
    q = II()
    for _ in range(q):
        (t, i, x) = GMI()
        x += 1
        if t:
            if nums2[i] != x:
                seg.apply(0, nums2[i] + 1, 1)
                seg.apply(0, x + 1, -1)
                nums2[i] = x
        elif nums1[i] != x:
            seg.apply(0, nums1[i] + 1, -1)
            seg.apply(0, x + 1, 1)
            nums1[i] = x
        print(seg.min_left(val + 1, lambda x: x <= 0) - 1)
    return
t = 1
for _ in range(t):
    main()