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 ≤ 10^5, 1 ≤ n ≤ 2000). 

Next n lines contain the description of black cells. The i-th of these lines contains numbers r_{i}, c_{i} (1 ≤ r_{i} ≤ h, 1 ≤ c_{i} ≤ 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 10^9 + 7.


-----Examples-----
Input
3 4 2
2 2
2 3

Output
2

Input
100 100 3
15 16
16 15
99 88

Output
545732279

Source: codeforces | Difficulty: HARD
Tags: Number theory

Combinatorics

Dynamic programming

Mathematics


Solutions:
(h, w, n) = list(map(int, input().split()))
l = [tuple(map(int, input().split())) for i in range(n)]
l.sort()
l += [(h, w)]
(N, B) = (h + w + 1 << 1, 10 ** 9 + 7)
(fac, inv) = ([1] * N, [1] * N)
for i in range(2, N):
	fac[i] = i * fac[i - 1] % B
	inv[i] = -(B // i) * inv[B % i] % B
for i in range(2, N):
	inv[i] = inv[i] * inv[i - 1] % B
C = lambda u, v: fac[u] * inv[v] % B * inv[u - v] % B
d = []
for i in range(n + 1):
	d += [C(l[i][0] + l[i][1] - 2, l[i][0] - 1)]
	for j in range(i):
		if l[j][1] <= l[i][1]:
			d[i] = (d[i] + B - d[j] * C(l[i][0] + l[i][1] - l[j][0] - l[j][1], l[i][0] - l[j][0]) % B) % B
print(d[n])


MOD = 10 ** 9 + 7
fact = [1] * 200013
for i in range(1, 200013):
	fact[i] = fact[i - 1] * i % MOD
inv = [1] * 200013
for i in range(2, 200013):
	inv[i] = -(MOD // i) * inv[MOD % i] % MOD
for i in range(2, 200013):
	inv[i] = inv[i] * inv[i - 1] % MOD

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

def rasch(x, y):
	nonlocal mas
	res = C(x + y - 2, x - 1) % MOD
	for i in mas:
		if x == i[0] and y == i[1]:
			break
		if i[0] <= x and i[1] <= y:
			l = C(x - i[0] + y - i[1], x - i[0])
			k = rasch(i[0], i[1]) if not i[3] else i[2]
			i[2] = k % MOD
			i[3] = 1
			res -= l * k % MOD
	return res % MOD
(h, w, n) = map(int, input().split(' '))
mas = []
for i in range(n):
	(x, y) = map(int, input().split(' '))
	mas.append([x, y, 0, 0])
mas.sort(key=lambda x: x[0] + x[1])
print(rasch(h, w) % MOD)


fact = [1]
rfact = [1]
MOD = int(1000000000.0) + 7
(n, m, k) = list(map(int, input().split()))
for i in range(1, max(2 * n, 2 * m) + 2):
	fact += [fact[-1] * i % MOD]
	rfact += [rfact[-1] * pow(i, MOD - 2, MOD) % MOD]

def cmb(n, k):
	return fact[n] * rfact[k] * rfact[n - k] % MOD
points = [tuple(map(int, input().split())) for i in range(k)]
points += [(n, m)]
points.sort()
dp = []
for i in range(k + 1):
	tmp = cmb(points[i][0] + points[i][1] - 2, points[i][0] - 1)
	for j in range(i):
		if points[j][0] <= points[i][0] and points[j][1] <= points[i][1]:
			tmp -= dp[j] * cmb(points[i][0] - points[j][0] + points[i][1] - points[j][1], points[i][1] - points[j][1]) % MOD
			tmp += MOD
			tmp %= MOD
	dp += [tmp]
print(dp[k])


from sys import stdin
input = stdin.buffer.readline
(f, inv) = ([1], [1, 1])
mod = 1000000007

def c(n, k):
	return f[n] * inv[k] * inv[n - k] % mod
(h, w, n) = map(int, input().split())
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
a = []
for i in range(n):
	a.append([*map(int, input().split())])
a.sort()
a.append([h, w])
dp = [0] * (n + 1)
for i in range(n + 1):
	dp[i] = c(a[i][0] + a[i][1] - 2, a[i][0] - 1)
	for j in range(0, i):
		if a[i][0] >= a[j][0] and a[i][1] >= a[j][1]:
			dp[i] -= dp[j] * c(a[i][0] - a[j][0] + a[i][1] - a[j][1], a[i][0] - a[j][0])
			dp[i] %= mod
print(dp[n])


MOD = 10 ** 9 + 7
fact = [1] * 200013
for i in range(1, 200013):
	fact[i] = fact[i - 1] * i % MOD
inv = [1] * 200013
for i in range(2, 200013):
	inv[i] = -(MOD // i) * inv[MOD % i] % MOD
for i in range(2, 200013):
	inv[i] = inv[i] * inv[i - 1] % MOD

def C(n, k):
	return fact[n] * inv[k] * inv[n - k] % MOD
(h, w, n) = map(int, input().split(' '))
mas = []
for i in range(n):
	(x, y) = map(int, input().split(' '))
	mas.append([x, y, 0, 0])
mas.append([h, w, 0, 0])
mas.sort(key=lambda x: x[0] + x[1])
for j in mas:
	j[2] = C(j[0] + j[1] - 2, j[0] - 1) % MOD
	for i in mas:
		if j[0] == i[0] and j[1] == i[1]:
			break
		if i[0] <= j[0] and i[1] <= j[1]:
			l = C(j[0] - i[0] + j[1] - i[1], j[0] - i[0]) % MOD
			k = i[2]
			j[2] -= l * k % MOD
print(mas[-1][2] % (10 ** 9 + 7))


fact = [1]
fTQJsiXxvUFMlBVGazWH = int
fTQJsiXxvUFMlBVGazWp = map
fTQJsiXxvUFMlBVGazWC = input
fTQJsiXxvUFMlBVGazWn = range
fTQJsiXxvUFMlBVGazWg = max
fTQJsiXxvUFMlBVGazWo = pow
fTQJsiXxvUFMlBVGazWu = tuple
fTQJsiXxvUFMlBVGazWI = print
rfact = [1]
MOD = fTQJsiXxvUFMlBVGazWH(1000000000.0) + 7
(n, m, k) = fTQJsiXxvUFMlBVGazWp(fTQJsiXxvUFMlBVGazWH, fTQJsiXxvUFMlBVGazWC().split())
for i in fTQJsiXxvUFMlBVGazWn(1, fTQJsiXxvUFMlBVGazWg(2 * n, 2 * m) + 2):
	fact += [fact[-1] * i % MOD]
	rfact += [rfact[-1] * fTQJsiXxvUFMlBVGazWo(i, MOD - 2, MOD) % MOD]

def cmb(n, k):
	return fact[n] * rfact[k] * rfact[n - k] % MOD
points = [fTQJsiXxvUFMlBVGazWu(fTQJsiXxvUFMlBVGazWp(fTQJsiXxvUFMlBVGazWH, fTQJsiXxvUFMlBVGazWC().split())) for i in fTQJsiXxvUFMlBVGazWn(k)]
points += [(n, m)]
points.sort()
dp = []
for i in fTQJsiXxvUFMlBVGazWn(k + 1):
	tmp = cmb(points[i][0] + points[i][1] - 2, points[i][0] - 1)
	for j in fTQJsiXxvUFMlBVGazWn(i):
		if points[j][0] <= points[i][0] and points[j][1] <= points[i][1]:
			tmp -= dp[j] * cmb(points[i][0] - points[j][0] + points[i][1] - points[j][1], points[i][1] - points[j][1]) % MOD
			tmp += MOD
			tmp %= MOD
	dp += [tmp]
fTQJsiXxvUFMlBVGazWI(dp[k])


MOD = 10 ** 9 + 7
fact = [1]
rfact = [1]
for i in range(1, 200500):
	fact.append(fact[-1] * i % MOD)
	rfact.append(rfact[-1] * pow(i, MOD - 2, MOD) % MOD)

def cnk(n, k):
	return fact[n] * rfact[k] * rfact[n - k] % MOD
(h, w, n) = list(map(int, input().split()))
points = []
for i in range(n):
	points.append(tuple(map(int, input().split())))
points = sorted(points)
points.append((h, w))
dp = [0 for i in range(len(points))]
for i in range(len(points)):
	dp[i] = cnk(points[i][0] + points[i][1] - 2, points[i][0] - 1)
	for j in range(i):
		if points[j][0] <= points[i][0] and points[j][1] <= points[i][1]:
			dp[i] -= dp[j] * cnk(points[i][0] + points[i][1] - points[j][0] - points[j][1], points[i][0] - points[j][0])
	dp[i] %= MOD
print(dp[-1])


def init_factorials(N, mod):
	f = 1
	fac = [1] * N
	for i in range(1, N):
		f *= i
		f %= mod
		fac[i] = f
	return fac

def init_inv(N, mod, fac):
	b = bin(mod - 2)[2:][-1::-1]
	ret = 1
	tmp = fac[N]
	if b[0] == '1':
		ret = fac[N]
	for bi in b[1:]:
		tmp *= tmp
		tmp %= mod
		if bi == '1':
			ret *= tmp
			ret %= mod
	inv = [1] * (N + 1)
	inv[N] = ret
	for i in range(N - 1, 0, -1):
		ret *= i + 1
		ret %= mod
		inv[i] = ret
	return inv

def f(r, c, mod, fac, inv):
	return fac[r + c] * inv[r] * inv[c] % mod

def read_data():
	(h, w, n) = list(map(int, input().split()))
	blacks = []
	for i in range(n):
		(r, c) = list(map(int, input().split()))
		blacks.append((r, c))
	return (h, w, n, blacks)

def solve(h, w, n, blacks):
	mod = 10 ** 9 + 7
	fac = init_factorials(h + w + 10, mod)
	inv = init_inv(h + w + 5, mod, fac)
	ans = fac[h + w - 2] * inv[h - 1] * inv[w - 1] % mod
	eb = [(r + c, r, c) for (r, c) in blacks]
	eb.sort()
	blacks = [(r, c) for (rc, r, c) in eb]
	g = [f(r - 1, c - 1, mod, fac, inv) for (r, c) in blacks]
	hw = h + w
	for (i, (r, c)) in enumerate(blacks):
		gi = g[i]
		rc = r + c
		ans -= gi * fac[hw - rc] * inv[h - r] * inv[w - c]
		ans %= mod
		for (j, (rj, cj)) in enumerate(blacks[i + 1:], i + 1):
			if r <= rj and c <= cj:
				g[j] -= gi * fac[rj + cj - rc] * inv[rj - r] * inv[cj - c]
				g[j] %= mod
	return ans
(h, w, n, blacks) = read_data()
print(solve(h, w, n, blacks))


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))
sys.setrecursionlimit(100000)
if sys.argv[-1] == '-ut':
	unittest.main(argv=[' '])
sys.stdout.write(calculate())


MOD = 10 ** 9 + 7
fact = [1] * 200013
for i in range(1, 200013):
	fact[i] = fact[i - 1] * i % MOD
inv = [1] * 200013
for i in range(2, 200013):
	inv[i] = -(MOD // i) * inv[MOD % i] % MOD
for i in range(2, 200013):
	inv[i] = inv[i] * inv[i - 1] % MOD

def combo(a, b):
	return fact[a] * inv[b] * inv[a - b] % MOD
(h, w, n) = map(int, input().split())
pt = []
for i in range(n):
	(r, c) = map(int, input().split())
	(r, c) = (r - 1, c - 1)
	pt.append(r * w + c)
pt.append(h * w - 1)
pt.sort()
dp = []
for i in range(n + 1):
	(r, c) = (pt[i] // w, pt[i] % w)
	dp.append(combo(r + c, r))
	for j in range(i):
		(r1, c1) = (pt[j] // w, pt[j] % w)
		if r1 <= r and c1 <= c:
			dp[i] -= dp[j] * combo(r + c - r1 - c1, r - r1)
	dp[i] %= MOD
print(dp[n])