Gerald and Giant Chess (Codeforces 560E)
Tags: DP, combinatorics

Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.

Input: The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.

Output: Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.


Sample Inputs:
3 4 2
2 2
2 3

100 100 3
15 16
16 15
99 88

Sample Outputs:
2

545732279

Solution (Python):
from sys import stdin, stdout
import collections, heapq, bisect, math
input = stdin.readline

def rint():
    return int(input())

def rstr():
    return input().strip()

def rlstr():
    return list(input().strip().split())

def rlint():
    return list(map(int, input().split()))
(f, inv) = ([1], [1, 1])
mod = 1000000007
for i in range(1, 200001):
    f.append(f[i - 1] * i % mod)
for i in range(2, 200001):
    inv.append(-(mod // i) * inv[mod % i] % mod)
for i in range(2, 200001):
    inv[i] *= inv[i - 1]
    inv[i] %= mod

def c(n, k):
    return f[n] * inv[k] * inv[n - k] % mod

def main():
    (h, w, n) = rlint()
    arr = []
    for _ in range(n):
        arr.append(rlint())
    arr.append([h, w])
    arr.sort()
    dp = [0] * (n + 1)
    for i in range(n + 1):
        dp[i] = c(arr[i][0] + arr[i][1] - 2, arr[i][0] - 1)
        for j in range(i):
            if arr[i][0] >= arr[j][0] and arr[i][1] >= arr[j][1]:
                dp[i] -= dp[j] * c(arr[i][0] - arr[j][0] + arr[i][1] - arr[j][1], arr[i][0] - arr[j][0])
                dp[i] %= mod
    print(dp[-1])
if __name__ == '__main__':
    main()

Solution (Python):
""""""
import unittest
import sys

class Chess:
    """"""
    N = 200001
    MOD = 10 ** 9 + 7

    def __init__(self, args):
        """"""
        (self.h, self.w, self.imax, self.numa, self.numb) = args
        self.pt = sorted(zip(self.numa, self.numb))
        self.pt.append((self.h, self.w))
        self.fact = [1]
        prev = 1
        for i in range(1, self.N):
            f = prev * i % self.MOD
            self.fact.append(f)
            prev = f
        self.inv = [0] * self.N
        self.inv[self.N - 1] = self.modInvfact(self.N - 1)
        for i in range(self.N - 2, -1, -1):
            self.inv[i] = self.inv[i + 1] * (i + 1) % self.MOD
        self.ways = []
        for i in range(len(self.pt)):
            (h, w) = self.pt[i]
            self.ways.append(self.modC(h + w - 2, h - 1))
            for j in range(i):
                (hj, wj) = self.pt[j]
                if hj <= h and wj <= w:
                    mult = self.modC(h - hj + w - wj, h - hj)
                    self.ways[i] = self.modSub(self.ways[i], self.ways[j] * mult, self.MOD)

    def modC(self, n, k):
        return self.fact[n] * (self.inv[k] * self.inv[n - k] % self.MOD) % self.MOD

    def modInvfact(self, n):
        return self.modExp(self.fact[n], self.MOD - 2, self.MOD)

    def modExp(self, n, e, p):
        res = 1
        while e > 0:
            if e % 2 == 1:
                res = res * n % p
            e >>= 1
            n = n * n % p
        return res

    def modSub(self, a, b, p):
        return ((a - b) % p + p) % p

    def calculate(self):
        """"""
        result = self.ways[-1]
        return str(result)

def get_inputs(test_inputs=None):
    it = iter(test_inputs.split('\n')) if test_inputs else None

    def uinput():
        """"""
        if it:
            return next(it)
        else:
            return sys.stdin.readline()
    (h, w, imax) = list(map(int, uinput().split()))
    numnums = list(map(int, ' '.join((uinput() for i in range(imax))).split()))
    numa = []
    numb = []
    for i in range(0, 2 * imax, 2):
        numa.append(numnums[i])
        numb.append(numnums[i + 1])
    return [h, w, imax, numa, numb]

def calculate(test_inputs=None):
    """"""
    return Chess(get_inputs(test_inputs)).calculate()

class unitTests(unittest.TestCase):

    def test_Chess_class__basic_functions(self):
        """"""
        d = Chess([3, 4, 2, [2, 2], [2, 3]])
        self.assertEqual(d.imax, 2)
        self.assertEqual(d.pt[0], (2, 2))
        self.assertEqual(d.modExp(3, 3, 6), 3)
        self.assertEqual(d.fact[3], 6)
        self.assertEqual(d.inv[3], d.modInvfact(3))
        self.assertEqual(d.modC(4, 2), 6)
        self.assertEqual(d.ways[0], 2)

    def test_sample_tests(self):
        """"""
        test = '3 4 2\n2 2\n2 3'
        self.assertEqual(calculate(test), '2')
        self.assertEqual(get_inputs(test)[0], 3)
        self.assertEqual(list(get_inputs(test)[3]), [2, 2])
        self.assertEqual(list(get_inputs(test)[4]), [2, 3])
        test = '100 100 3\n15 16\n16 15\n99 88'
        self.assertEqual(calculate(test), '545732279')
        test = '1\n12'
        test = '1\n12'

    def test_time_limit_test(self):
        """"""
        import random
        imax = 2000
        h = 100000
        w = 99000
        num = str(imax)
        test = str(h) + ' ' + str(w) + ' ' + num + '\n'
        numnums = [str(i) + ' ' + str(i + 1) for i in range(imax)]
        test += '\n'.join(numnums) + '\n'
        import timeit
        start = timeit.default_timer()
        args = get_inputs(test)
        init = timeit.default_timer()
        d = Chess(args)
        calc = timeit.default_timer()
        d.calculate()
        stop = timeit.default_timer()
        print('\nTime Test: ' + '{0:.3f}s (inp {1:.3f}s init {2:.3f}s calc {3:.3f}s)'.format(stop - start, init - start, calc - init, stop - calc))
if __name__ == '__main__':
    sys.setrecursionlimit(100000)
    if sys.argv[-1] == '-ut':
        unittest.main(argv=[' '])
    sys.stdout.write(calculate())

Solution (Python):
from __future__ import annotations
import math

def solution(height: int, width: int, black_points: list[tuple[int]], modulo: int) -> int:
    length = height + width
    factorial = [1] * length
    for i in range(1, length):
        factorial[i] = factorial[i - 1] * i % modulo
    inverse = [1] * length
    for i in range(2, length):
        inverse[i] = (modulo - modulo // i) * inverse[modulo % i] % modulo
    for i in range(1, length):
        inverse[i] = inverse[i] * inverse[i - 1] % modulo
    math_comb = lambda n, k: factorial[n] * inverse[k] * inverse[n - k] % modulo
    math_comb2 = lambda n, k: math.comb(n, k) % modulo
    black_points.append((height, width))
    black_points.sort()
    total_paths = [0] * len(black_points)
    for (i, (h_i, w_i)) in enumerate(black_points):
        total_paths[i] = math_comb(h_i - 1 + w_i - 1, h_i - 1) % modulo
        for (j, (h_j, w_j)) in enumerate(black_points[:i]):
            if h_i >= h_j and w_i >= w_j:
                total_paths[i] -= total_paths[j] * math_comb(h_i - h_j + w_i - w_j, h_i - h_j) % modulo
    return total_paths[-1] % modulo

def main():
    modulo = 1000000007
    (height, width, black_points_cnt) = list(map(int, input().split()))
    black_points = []
    for _ in range(black_points_cnt):
        (row_num, col_num) = list(map(int, input().split()))
        black_points.append((row_num, col_num))
    print(solution(height, width, black_points, modulo))
    return 0
if __name__ == '__main__':
    main()