Optimize! (Codeforces 338E)
Tags: Others, data structures

Manao is solving a problem with the following statement:  He came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem:getAnswer(a[1..n], b[1..len], h)  answer = 0  for i = 1 to n-len+1    answer = answer + f(a[i..i+len-1], b, h, 1)  return answerf(s[1..len], b[1..len], h, index)  if index = len+1 then    return 1  for i = 1 to len    if s[index] + b[i] >= h      mem = b[i]      b[i] = 0      res = f(s, b, h, index + 1)      b[i] = mem      if res > 0        return 1  return 0Your task is to help Manao optimize his algorithm.

Input: The first line contains space-separated integers n, len and h (1 ≤ len ≤ n ≤ 150000; 1 ≤ h ≤ 109). The second line contains len space-separated integers b1, b2, ..., blen (1 ≤ bi ≤ 109). The third line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Output: Print a single number — the answer to Manao's problem.


Sample Inputs:
5 2 10
5 3
1 8 5 5 7

Sample Outputs:
2

Solution (Python):
from bisect import bisect_left
import sys
readline = sys.stdin.readline

class Lazy_Segment_Tree:

    def __init__(self, N, f, e, f_act, e_act, operate):
        self.N = N
        self.f = f
        self.e = e
        self.f_act = f_act
        self.e_act = e_act
        self.operate = operate
        self.segment_tree = [self.e] * (self.N + self.N)
        self.segment_tree_act = [self.e_act] * (self.N + self.N)

    def __getitem__(self, i):
        if type(i) is int:
            if -self.N <= i < 0:
                i += self.N * 2
            elif 0 <= i < self.N:
                i += self.N
            else:
                raise IndexError('list index out of range')
            self.Propagate_Above(i)
            self.Recalculate_Above(i)
            return self.Operate_At(i)
        else:
            (a, b, c) = (i.start, i.stop, i.step)
            if a == None or a < -self.N:
                a = self.N
            elif self.N <= a:
                a = self.N * 2
            elif a < 0:
                a += self.N * 2
            else:
                a += self.N
            if b == None or self.N <= b:
                b = self.N * 2
            elif b < -self.N:
                b = self.N
            elif b < 0:
                b += self.N * 2
            else:
                b += self.N
            return self.segment_tree[slice(a, b, c)]

    def __setitem__(self, i, x):
        if -self.N <= i < 0:
            i += self.N * 2
        elif 0 <= i < self.N:
            i += self.N
        else:
            raise IndexError('list index out of range')
        self.Propagate_Above(i)
        self.segment_tree[i] = x
        self.segment_tree_act[i] = self.e_act
        self.Recalculate_Above(i)

    def Operate_At(self, i):
        return self.operate(self.segment_tree[i], self.segment_tree_act[i])

    def Propagate_At(self, i):
        self.segment_tree[i] = self.Operate_At(i)
        self.segment_tree_act[i << 1] = self.f_act(self.segment_tree_act[i << 1], self.segment_tree_act[i])
        self.segment_tree_act[i << 1 | 1] = self.f_act(self.segment_tree_act[i << 1 | 1], self.segment_tree_act[i])
        self.segment_tree_act[i] = self.e_act

    def Propagate_Above(self, i):
        H = i.bit_length() - 1
        for h in range(H, 0, -1):
            self.Propagate_At(i >> h)

    def Recalculate_Above(self, i):
        while i > 1:
            i >>= 1
            self.segment_tree[i] = self.f(self.Operate_At(i << 1), self.Operate_At(i << 1 | 1))

    def Build(self, lst):
        for (i, x) in enumerate(lst, self.N):
            self.segment_tree[i] = x
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])
        self.segment_tree_act = [self.e_act] * (self.N + self.N)

    def Fold(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        self.Propagate_Above(L // (L & -L))
        self.Propagate_Above(R // (R & -R) - 1)
        vL = self.e
        vR = self.e
        while L < R:
            if L & 1:
                vL = self.f(vL, self.Operate_At(L))
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.Operate_At(R), vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def Fold_Index(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        if L == R:
            return None
        x = self.Fold(L - self.N, R - self.N)
        while L < R:
            if L & 1:
                if self.segment_tree[L] == x:
                    i = L
                    break
                L += 1
            if R & 1:
                R -= 1
                if self.segment_tree[R] == x:
                    i = R
                    break
            L >>= 1
            R >>= 1
        while i < self.N:
            if self.segment_tree[i] == self.segment_tree[i << 1]:
                i <<= 1
            else:
                i <<= 1
                i |= 1
        i -= self.N
        return i

    def Operate_Range(self, a, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        L0 = L // (L & -L)
        R0 = R // (R & -R) - 1
        self.Propagate_Above(L0)
        self.Propagate_Above(R0)
        while L < R:
            if L & 1:
                self.segment_tree_act[L] = self.f_act(self.segment_tree_act[L], a)
                L += 1
            if R & 1:
                R -= 1
                self.segment_tree_act[R] = self.f_act(self.segment_tree_act[R], a)
            L >>= 1
            R >>= 1
        self.Recalculate_Above(L0)
        self.Recalculate_Above(R0)

    def Update(self):
        for i in range(1, self.N):
            self.Propagate_At(i)
        for i in range(self.N, self.N * 2):
            self.segment_tree[i] = self.Operate_At(i)
            self.segment_tree_act[i] = self.e_act
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def __str__(self):
        self.Update()
        return '[' + ', '.join(map(str, [self.operate(x, a) for (x, a) in zip(self.segment_tree[self.N:], self.segment_tree_act[self.N:])])) + ']'
(N, M, H) = map(int, readline().split())
B = list(map(int, readline().split()))
A = list(map(int, readline().split()))
ans = 0
B.sort()
inf = 1 << 30
LST = Lazy_Segment_Tree(M, min, inf, lambda x, y: x + y, 0, lambda x, a: x + a)
LST.Build([-i - 1 for i in range(M)])
for a in A[:M]:
    LST.Operate_Range(1, bisect_left(B, H - a))
if LST.Fold() >= 0:
    ans += 1
for (a, aa) in zip(A[M:], A[:-M]):
    LST.Operate_Range(1, bisect_left(B, H - a))
    LST.Operate_Range(-1, bisect_left(B, H - aa))
    if LST.Fold() >= 0:
        ans += 1
print(ans)

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 0)
(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='')

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
(n, m, h) = MII()
nums2 = LII()
nums1 = LII()
for i in range(m):
    nums2[i] = h - nums2[i]
nums2.sort()
tmp = [0] * m
for i in range(m):
    p = bisect.bisect_right(nums2, nums1[i]) - 1
    if p >= 0:
        tmp[p] += 1
for i in range(m - 1, 0, -1):
    tmp[i - 1] += tmp[i]
for i in range(m):
    tmp[i] -= m - 1 - i
inf = m
seg = LazySegTree(min, inf, add, add, 0, tmp)
ans = 1 if seg.all_prod() > 0 else 0
for i in range(n - m):
    seg.apply(0, bisect.bisect_right(nums2, nums1[i]), -1)
    seg.apply(0, bisect.bisect_right(nums2, nums1[i + m]), 1)
    ans += 1 if seg.all_prod() > 0 else 0
print(ans)

Solution (Python):
from bisect import bisect_left
import sys
readline = sys.stdin.readline

class Lazy_Segment_Tree:

    def __init__(self, N, f, e, f_act, e_act, operate):
        self.N = N
        self.f = f
        self.e = e
        self.f_act = f_act
        self.e_act = e_act
        self.operate = operate
        self.segment_tree = [self.e] * (self.N + self.N)
        self.segment_tree_act = [self.e_act] * (self.N + self.N)

    def __getitem__(self, i):
        if type(i) is int:
            if -self.N <= i < 0:
                i += self.N * 2
            elif 0 <= i < self.N:
                i += self.N
            else:
                raise IndexError('list index out of range')
            self.Propagate_Above(i)
            self.Recalculate_Above(i)
            return self.Operate_At(i)
        else:
            (a, b, c) = (i.start, i.stop, i.step)
            if a == None or a < -self.N:
                a = self.N
            elif self.N <= a:
                a = self.N * 2
            elif a < 0:
                a += self.N * 2
            else:
                a += self.N
            if b == None or self.N <= b:
                b = self.N * 2
            elif b < -self.N:
                b = self.N
            elif b < 0:
                b += self.N * 2
            else:
                b += self.N
            return self.segment_tree[slice(a, b, c)]

    def __setitem__(self, i, x):
        if -self.N <= i < 0:
            i += self.N * 2
        elif 0 <= i < self.N:
            i += self.N
        else:
            raise IndexError('list index out of range')
        self.Propagate_Above(i)
        self.segment_tree[i] = x
        self.segment_tree_act[i] = self.e_act
        self.Recalculate_Above(i)

    def Operate_At(self, i):
        return self.operate(self.segment_tree[i], self.segment_tree_act[i])

    def Propagate_At(self, i):
        self.segment_tree[i] = self.Operate_At(i)
        self.segment_tree_act[i << 1] = self.f_act(self.segment_tree_act[i << 1], self.segment_tree_act[i])
        self.segment_tree_act[i << 1 | 1] = self.f_act(self.segment_tree_act[i << 1 | 1], self.segment_tree_act[i])
        self.segment_tree_act[i] = self.e_act

    def Propagate_Above(self, i):
        H = i.bit_length() - 1
        for h in range(H, 0, -1):
            self.Propagate_At(i >> h)

    def Recalculate_Above(self, i):
        while i > 1:
            i >>= 1
            self.segment_tree[i] = self.f(self.Operate_At(i << 1), self.Operate_At(i << 1 | 1))

    def Build(self, lst):
        for (i, x) in enumerate(lst, self.N):
            self.segment_tree[i] = x
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])
        self.segment_tree_act = [self.e_act] * (self.N + self.N)

    def Fold(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        self.Propagate_Above(L // (L & -L))
        self.Propagate_Above(R // (R & -R) - 1)
        vL = self.e
        vR = self.e
        while L < R:
            if L & 1:
                vL = self.f(vL, self.Operate_At(L))
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.Operate_At(R), vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def Fold_Index(self, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        if L == R:
            return None
        x = self.Fold(L - self.N, R - self.N)
        while L < R:
            if L & 1:
                if self.segment_tree[L] == x:
                    i = L
                    break
                L += 1
            if R & 1:
                R -= 1
                if self.segment_tree[R] == x:
                    i = R
                    break
            L >>= 1
            R >>= 1
        while i < self.N:
            if self.segment_tree[i] == self.segment_tree[i << 1]:
                i <<= 1
            else:
                i <<= 1
                i |= 1
        i -= self.N
        return i

    def Operate_Range(self, a, L=None, R=None):
        if L == None or L < -self.N:
            L = self.N
        elif self.N <= L:
            L = self.N * 2
        elif L < 0:
            L += self.N * 2
        else:
            L += self.N
        if R == None or self.N <= R:
            R = self.N * 2
        elif R < -self.N:
            R = self.N
        elif R < 0:
            R += self.N * 2
        else:
            R += self.N
        L0 = L // (L & -L)
        R0 = R // (R & -R) - 1
        self.Propagate_Above(L0)
        self.Propagate_Above(R0)
        while L < R:
            if L & 1:
                self.segment_tree_act[L] = self.f_act(self.segment_tree_act[L], a)
                L += 1
            if R & 1:
                R -= 1
                self.segment_tree_act[R] = self.f_act(self.segment_tree_act[R], a)
            L >>= 1
            R >>= 1
        self.Recalculate_Above(L0)
        self.Recalculate_Above(R0)

    def Update(self):
        for i in range(1, self.N):
            self.Propagate_At(i)
        for i in range(self.N, self.N * 2):
            self.segment_tree[i] = self.Operate_At(i)
            self.segment_tree_act[i] = self.e_act
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def __str__(self):
        self.Update()
        return '[' + ', '.join(map(str, [self.operate(x, a) for (x, a) in zip(self.segment_tree[self.N:], self.segment_tree_act[self.N:])])) + ']'
(N, M, H) = map(int, readline().split())
B = list(map(int, readline().split()))
A = list(map(int, readline().split()))
ans = 0
B.sort()
inf = 1 << 30
LST = Lazy_Segment_Tree(M, min, inf, lambda x, y: x + y, 0, lambda x, a: x + a)
LST.Build([-i - 1 for i in range(M)])
for a in A[:M]:
    LST.Operate_Range(1, bisect_left(B, H - a))
if LST.Fold() >= 0:
    ans += 1
for (a, aa) in zip(A[M:], A[:-M]):
    LST.Operate_Range(1, bisect_left(B, H - a))
    LST.Operate_Range(-1, bisect_left(B, H - aa))
    if LST.Fold() >= 0:
        ans += 1
print(ans)