Problem:


Score : 600 points

Problem Statement

There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print -1 instead.

Constraints

1 \leq H,W \leq 2\times 10^5

1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:

H W
A_1 B_1
A_2 B_2
:
A_H B_H

Output

Print H lines. The i-th line should contain the answer for the case k=i.

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let (i,j) denote the square at the i-th row from the top and j-th column from the left.

For k=1, we need one move such as (1,1) → (2,1).

For k=2, we need three moves such as (1,1) → (2,1) → (2,2) → (3,2).

For k=3, we need six moves such as (1,1) → (2,1) → (2,2) → (3,2) → (3,3) → (3,4) → (4,4).

For k=4, it is impossible to reach any square in the fifth row from the top.



Sample input:
4 4
2 4
1 1
2 3
2 4


Sample output:
1
3
6
-1

Submission status: Accepted

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mat = lambda x, y, v: [[v]*y for _ in range(x)]
ten = lambda x, y, z, v: [mat(y, z, v) for _ in range(x)]
mod = 1000000007
sys.setrecursionlimit(1000000)

class BIT:
    def __init__(self, n):
        self.n = n
        self.nums = [0] * (n+1)
        
    def add(self, i, x):
        n, nums = self.n, self.nums
        i += 1
        while i <= n:
            nums[i] += x
            i += i & -i
    
    def sum(self, i):
        nums = self.nums
        s = 0
        i += 1
        while i:
            s += nums[i]
            i -= i & -i
        return s
    
    def search(self, x):
        # minimum index i such that x <= self.sum(i)
        n, nums = self.n, self.nums
        s, p = 0, 0
        for i in range(n.bit_length(), -1, -1):
            np = p + (1<<i)
            if np <= n and s+nums[np] < x:
                s += nums[np]
                p = np
        return p

class MultiSet:
    def __init__(self, n):
        self.bit = BIT(n)

    def insert(self, key):
        self.bit.add(key, 1)

    def erase(self, key):
        self.bit.add(key, -1)

    def top(self, i=0):
        # i-th smallest element
        return self.bit.search(i+1)

    def size(self):
        return self.bit.sum(self.bit.n-1)

    def count(self, key):
        # number of keys
        return self.bit.sum(key)-self.bit.sum(key-1)

    def lower_bound(self, key):
        # minimum key k no less than key (key <= k)
        return self.bit.search(self.bit.sum(key-1)+1)

    def upper_bound(self, key):
        # minimum key k greater than key (key < k)
        return self.bit.search(self.bit.sum(key)+1)

    def debug(self):
        vals = []
        for i in range(self.bit.n):
            key = self.top(i)
            if key == self.bit.n: break
            vals.append(key)
        print(vals)

class Map(MultiSet):
    def __init__(self, n):
        super().__init__(n)
        self.data = {}

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, val):
        self.insert(key, val)

    def insert(self, key, val=None):
        if key not in self.data:
            super().insert(key)
        self.data[key] = val

    def erase(self, key):
        if key in self.data:
            super().erase(key)
            del self.data[key]

    def debug(self):
        vals = []
        for i in range(self.bit.n):
            key = self.top(i)
            if key == self.bit.n: break
            vals.append((key, self[key]))
        print(vals)

H, W = rl()
walls = []
for i in range(H):
    a, b = rl()
    a, b = a-1, b-1
    walls.append((a,b))

mp = Map(W)
for i in range(W):
    mp[i] = i
ms = MultiSet(W)
for i in range(W):
    ms.insert(0)

for idx, (a, b) in enumerate(walls):
    i = mp.lower_bound(a)
    r = -1
    #print('mp:', end='')
    #mp.debug()
    #print('ms:', end='')
    #ms.debug()
    while i < W and i <= b+1:
        r = max(r, mp[i])
        ms.erase(i-mp[i])
        mp.erase(i)
        i = mp.lower_bound(i)
    if r != -1 and b+1 < W:
        ms.insert(b+1-r)
        mp[b+1] = r
    ans = -1
    if ms.size() > 0:
        ans = ms.top() + idx + 1
    print(ans)

Submission status: Accepted

Solution code:
import numpy as np
i4 = np.int32
i8 = np.int64


def solve(a, b, H, W):
    ret = np.empty(H, i8)
    for i in range(H):
        ret[i] = -1
    dp0 = np.arange(W)
    dp = np.arange(W)
    arg0 = W - 1
    arg = 0
    for i in range(H):
        r1 = np.searchsorted(dp, a[i])
        r2 = np.searchsorted(dp, b[i])
        if b[i] == W:
            if r1 == 0:
                return ret
            else:
                dp0 = dp0[: r1]
                dp = dp[: r1]
        else:
            dp[r1:r2] = b[i]

        if arg0 > -1:
            if r1 <= arg0 < r2:
                for j in range(r1 - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        ret[i] = i + 1
                        break
                else:
                    arg0 = -1
                    arg = np.argmin(dp - dp0)
                    ret[i] = dp[arg] - dp0[arg] + i + 1
            else:
                ret[i] = i + 1
        else:
            if r1 <= arg < r2:
                arg = np.argmin(dp - dp0)
            ret[i] = dp[arg] - dp0[arg] + i + 1

        if i % 1000 == 999:
            m = 0
            prev = dp[0]
            for k in range(1, dp.shape[0]):
                if dp[k] > prev:
                    dp0[m] = dp0[k - 1]
                    dp[m] = prev
                    m += 1
                    prev = dp[k]
            else:
                dp0[m] = dp0[dp0.shape[0] - 1]
                dp[m] = prev
                m += 1
            dp0 = dp0[: m]
            dp = dp[: m]
            if arg0 > -1:
                for j in range(m - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        break
            else:
                arg = np.argmin(dp - dp0)
    return ret


def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ab = np.fromstring(stdin.read(), i8, sep=' ').reshape((-1, 2)).T.copy()
    ans = solve(ab[0] - 1, ab[1], H, W)
    p = '\n'.join([str(x) for x in ans.tolist()])
    print(p)


def cc_export():
    from numba.pycc import CC
    from numba.types import Array, int64
    cc = CC('my_module')
    cc.export('solve', (Array(int64, 1, 'C'), Array(int64, 1, 'C'), int64, int64))(solve)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import solve
    main('/dev/stdin')

Submission status: Accepted

Solution code:
import numpy as np
from numba import njit
from numba.types import Array, int64
i4 = np.int32
i8 = np.int64


@njit((Array(int64, 1, 'C'), Array(int64, 1, 'C'), int64, int64), cache=True)
def solve(a, b, H, W):
    ret = np.empty(H, i8)
    for i in range(H):
        ret[i] = -1
    dp0 = np.arange(W)
    dp = np.arange(W)
    arg0 = W - 1
    arg = 0
    for i in range(H):
        r1 = np.searchsorted(dp, a[i])
        r2 = np.searchsorted(dp, b[i])
        if b[i] == W:
            if r1 == 0:
                return ret
            else:
                dp0 = dp0[: r1]
                dp = dp[: r1]
        else:
            dp[r1:r2] = b[i]

        if arg0 > -1:
            if r1 <= arg0 < r2:
                for j in range(r1 - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        ret[i] = i + 1
                        break
                else:
                    arg0 = -1
                    arg = np.argmin(dp - dp0)
                    ret[i] = dp[arg] - dp0[arg] + i + 1
            else:
                ret[i] = i + 1
        else:
            if r1 <= arg < r2:
                arg = np.argmin(dp - dp0)
            ret[i] = dp[arg] - dp0[arg] + i + 1

        if i % 1000 == 999:
            m = 0
            prev = dp[0]
            for k in range(1, dp.shape[0]):
                if dp[k] > prev:
                    dp0[m] = dp0[k - 1]
                    dp[m] = prev
                    m += 1
                    prev = dp[k]
            else:
                dp0[m] = dp0[dp0.shape[0] - 1]
                dp[m] = prev
                m += 1
            dp0 = dp0[: m]
            dp = dp[: m]
            if arg0 > -1:
                for j in range(m - 1, -1, -1):
                    if dp[j] == dp0[j]:
                        arg0 = j
                        break
            else:
                arg = np.argmin(dp - dp0)
    return ret


def main(in_file):
    stdin = open(in_file)
    H, W = [int(x) for x in stdin.readline().split()]
    ab = np.fromstring(stdin.read(), i8, sep=' ').reshape((-1, 2)).T
    ans = solve(ab[0] - 1, ab[1].copy(), H, W)
    p = '\n'.join([str(x) for x in ans.tolist()])
    print(p)


if __name__ == '__main__':
    main('/dev/stdin')