Problem:


Score : 100 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns.
Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.

In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Constraints

All values in input are integers.

2 \leq H, W \leq 10^5

1 \leq N \leq 3000

1 \leq r_i \leq H

1 \leq c_i \leq W

Squares (r_i, c_i) are all distinct.

Squares (1, 1) and (H, W) are empty squares.

Input

Input is given from Standard Input in the following format:

H W N
r_1 c_1
r_2 c_2
:
r_N c_N

Output

Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Sample Input 1

3 4 2
2 2
1 4

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2 2
2 1
4 2

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5 4
3 1
3 5
1 3
5 3

Sample Output 3

24

Sample Input 4

100000 100000 1
50000 50000

Sample Output 4

123445622

Be sure to print the count modulo 10^9 + 7.



Sample input:
3 4 2
2 2
1 4


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
from functools import lru_cache
@lru_cache(maxsize = None)
def cmb(n, r):
    #if ( r<0 or r>n ):
    #    return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] # 逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)-1):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        if y1 <= y2:
            #dx = x2 - x1 + 1
            #dy = y2 - y1 + 1
            #dv = v1 * cmb(dx+dy-2,dy-1)
            #maplst[j][2] = v2-dv
            maplst[j][2] = v2 - v1 * cmb(x2-x1+y2-y1,y2-y1)

print(maplst[-1][2] % mod)

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
def cmb(n, r):
    #if ( r<0 or r>n ):
    #    return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] # 逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)-1):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        if y1 <= y2:
            maplst[j][2] = v2 - v1 * cmb(x2-x1+y2-y1,y2-y1)

print(maplst[-1][2] % mod)

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
def cmb(n, r):
    #if ( r<0 or r>n ):
    #    return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] # 逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(N):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,N+1):
        x2,y2,v2 = maplst[j]
        if y1 <= y2:
            maplst[j][2] = v2 - v1 * cmb((x2-x1+1)+(y2-y1+1)-2,(y2-y1+1)-1)

print(maplst[-1][2] % mod)

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
def cmb(n, r):
    #if ( r<0 or r>n ):
    #    return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        if y1 <= y2:
            maplst[j][2] = v2 - v1 * cmb((x2-x1+1)+(y2-y1+1)-2,(y2-y1+1)-1)

print(maplst[-1][2] % mod)

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        maplst[j][2] -= v1 * cmb((x2-x1+1)+(y2-y1+1)-2,(y2-y1+1)-1)

print(maplst[-1][2] % (10**9+7))

Submission status: Time Limit Exceeded

Solution code:
def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
#-------------------------------------------------------

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        maplst[j][2] = v2- v1 * cmb((x2-x1+1)+(y2-y1+1)-2,(y2-y1+1)-1)

print(maplst[-1][2] % (10**9+7))

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
#   https://qiita.com/derodero24/items/91b6468e66923a87f39f より
def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
#-------------------------------------------------------

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
for i in range(N):
    x,y = map(int, input().split())
    maplst.append([x,y,cmb(x+y-2,y-1)])
maplst.append([H,W,cmb(H+W-2,W-1)])
maplst.sort()

#壁の分を減算
for i in range(len(maplst)):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
        dx = x2 - x1 + 1
        dy = y2 - y1 + 1
        dv = v1 * cmb(dx+dy-2,dy-1)
        maplst[j][2] = v2-dv

print(maplst[-1][2] % (10**9+7))

Submission status: Time Limit Exceeded

Solution code:
#-----conbination計算部分------
#   https://qiita.com/derodero24/items/91b6468e66923a87f39f より

def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#-------------------------------------------------------

#入力
H,W,N = map(int, input().split())
#迷路の初期化
maplst = []
maplst.append([H,W,cmb(H+W-2,W-1)])
for i in range(N):
    x,y = map(int, input().split())
    keystr = str(x).zfill(6)+str(y).zfill(6)
    maplst.append([x,y,cmb(x+y-2,y-1)])

maplst.sort()

#壁の分を減算
for i in range(len(maplst)):
    x1,y1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        x2,y2,v2 = maplst[j]
#        if x1 > x2 or y1 > y2 or (x1 == x2 and y1 == y2):
#            continue
        dx = x2 - x1 + 1
        dy = y2 - y1 + 1
        dv = v1 * cmb(dx+dy-2,dy-1)
        #maplst[j] = [ks2,x2,y2,a2,v2-dv]
        maplst[j][2] = v2-dv

print(maplst[-1][2] % mod)

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter
H,W,N = map(int, input().split())

#迷路の初期化
keystr = str(H).zfill(6)+str(W).zfill(6)
maplst = []
maplst.append([keystr,H,W,"G",0])
for i in range(N):
    x,y = map(int, input().split())
    keystr = str(x).zfill(6)+str(y).zfill(6)
    maplst.append([keystr,x,y,"W",0])

maplst.sort(key=itemgetter(0))

#-----conbination計算部分------
#   https://qiita.com/derodero24/items/91b6468e66923a87f39f より

def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 10**5*2
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#-------------------------------------------------------

#壁無しの場合の計算
for i in range(len(maplst)):
    ks1,x1,y1,a1,v1 = maplst[i]
#    maplst[i] = [ks1,x1,y1,a1,cmb(x1+y1-2,y1-1)]
    maplst[i][4] = cmb(x1+y1-2,y1-1)

#壁の分を減算
for i in range(len(maplst)):
    ks1,x1,y1,a1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        ks2,x2,y2,a2,v2 = maplst[j]
#        if x1 > x2 or y1 > y2 or (x1 == x2 and y1 == y2):
#            continue
        dx = x2 - x1 + 1
        dy = y2 - y1 + 1
        dv = v1 * cmb(dx+dy-2,dy-1)
        #maplst[j] = [ks2,x2,y2,a2,v2-dv]
        maplst[j][4] = v2-dv

print(maplst[-1][4] % mod)

Submission status: Time Limit Exceeded

Solution code:
from operator import itemgetter
H,W,N = map(int, input().split())

#迷路の初期化
keystr = str(H).zfill(6)+str(W).zfill(6)
maplst = []
maplst.append([keystr,H,W,"G",0])
for i in range(N):
    x,y = map(int, input().split())
    keystr = str(x).zfill(6)+str(y).zfill(6)
    maplst.append([keystr,x,y,"W",0])

maplst.sort(key=itemgetter(0))

#-----conbination計算部分------
#   https://qiita.com/derodero24/items/91b6468e66923a87f39f より

def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 2*10**5+1
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

#-------------------------------------------------------

#壁無しの場合の計算
for i in range(len(maplst)):
    ks1,x1,y1,a1,v1 = maplst[i]
    maplst[i] = [ks1,x1,y1,a1,cmb(x1+y1-2,y1-1)]

#壁の分を減算
for i in range(len(maplst)):
    ks1,x1,y1,a1,v1 = maplst[i]
    for j in range(i+1,len(maplst)):
        ks2,x2,y2,a2,v2 = maplst[j]
#        if x1 > x2 or y1 > y2 or (x1 == x2 and y1 == y2):
#            continue
        dx = x2 - x1 + 1
        dy = y2 - y1 + 1
        dv = v1 * cmb(dx+dy-2,dy-1)
        maplst[j] = [ks2,x2,y2,a2,v2-dv]

print(maplst[-1][4] % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
H,W,N = map(int, input().split())

#迷路の初期化
mapdic = {(H,W):["G",0]}
for i in range(N):
    x,y = map(int, input().split())
    mapdic[x,y] = ["W",0]

'''-----conbination計算部分------
   https://qiita.com/derodero24/items/91b6468e66923a87f39f より
'''   
def cmb(n, r, mod=10**9+7):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9+7 #出力の制限
N = 2*10**5+1
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

'''-------------------------------------------------------'''

'''壁無しの場合の計算'''
for (x1,y1) ,[a1,v1] in mapdic.items():
    mapdic[(x1,y1)] = [a1,cmb(x1+y1-2,y1-1)]


'''壁の分を減算'''
for (x1,y1) in sorted(mapdic.keys()):
    v1 = mapdic[(x1,y1)][1]
    for (x2,y2) in sorted(mapdic.keys()):
        if x1 > x2 or y1 > y2 or (x1 == x2 and y1 == y2):
            continue
        v2 = mapdic[(x2,y2)][1]
        dx = x2 - x1 + 1
        dy = y2 - y1 + 1
        dv = v1 * cmb(dx+dy-2,dy-1)
        mapdic[(x2,y2)][1] = v2 - dv

print(mapdic[H,W][1] % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
H,W,N = map(int, input().split())

#迷路の初期化
mapdic = {(H,W):"G"}
for i in range(N):
    x,y = map(int, input().split())
    mapdic[x,y] = "W"

#print(mapdic)

#dpの初期化
dp = [[0] * (H+2), [0] * (H+2)]
dp[0][1] = 1

def mapchk_sum(x,y,a,b):
    if (x,y) in mapdic.keys():
        if mapdic[x,y] == "W":
            return 0
        elif mapdic[x,y] == "G":
            print((a+b) % (10**9+7))
            sys.exit()
        else:
            print("mapchk_ERROR")
            sys.exit()
    else:
        return (a+b) % (10**9+7)

def do_step(w,frm,to):
    startx = max(1, 1 + w - W)
    for x in range(startx,H+1):
        y = w + 1 - x
        if y < 1 or y > W:
                dp[to][x] = 0
                break
        else:
            dp[to][x] = mapchk_sum(x,y,dp[frm][x-1],dp[frm][x])
frm,to = 0,1
for w in range(2,max(H,W)*2+1):
    do_step(w,frm,to)
    #print(dp[frm],dp[to])
    frm,to = to,frm

Submission status: Time Limit Exceeded

Solution code:
import sys
H,W,N = map(int, input().split())

#迷路の初期化
mapdic = {(H,W):"G"}
for i in range(N):
    x,y = map(int, input().split())
    mapdic[x,y] = "W"

#print(mapdic)

#dpの初期化
dp = [[0] * (H+2), [0] * (H+2)]
dp[0][1] = 1

def mapchk_sum(x,y,a,b):
    if (x,y) in mapdic.keys():
        if mapdic[x,y] == "W":
            return 0
        elif mapdic[x,y] == "G":
            print((a+b) % (10**9+7))
            sys.exit()
        else:
            print("mapchk_ERROR")
            sys.exit()
    else:
        return (a+b) % (10**9+7)

def do_step(w,frm,to):
    startx = max(1, 1 + w - W)
    for x in range(startx,H+1):
        y = w + 1 - x
        if y < 1 or y > W:
                dp[to][x] = 0
                break
        elif x == 1 or y == 1:
            dp[to][x] = mapchk_sum(x,y,dp[frm][x-1],dp[frm][x])
        else:
            dp[to][x] = mapchk_sum(x,y,dp[frm][x-1],dp[frm][x])
frm,to = 0,1
for w in range(2,max(H,W)*2+1):
    do_step(w,frm,to)
    #print(dp[frm],dp[to])
    frm,to = to,frm

Submission status: Time Limit Exceeded

Solution code:
class Combination:
    '''MOD上の
    計算量：階乗・逆元テーブルの作成O(N)
    nCkを求めるO(1)'''

    def __init__(self, n, MOD):
        self.fact = [1] * (n + 1)
        for i in range(1, n + 1):
            self.fact[i] = self.fact[i-1] * i % MOD
        self.inv_fact = [pow(self.fact[i], MOD - 2, MOD) for i in range(n + 1)]
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


h, w, n = map(int, input().split())
info = [(1, 1)] + [tuple(map(int, input().split())) for i in range(n)] + [(h, w)]
n += 2
MOD = 10**9 + 7
comb = Combination(w+h+1, MOD)

dp = {}
dp[0] = (0, 1)
def solve(ind):
    if ind in dp:
        return dp[ind]
    i, j = info[ind]
    dp0 = 0
    dp1 = 0
    for ind2 in range(n):
        if ind2 == ind:
            continue
        pi, pj = info[ind2]
        if pi <= i and pj <= j:
            tmp = comb.combination((i+j)-(pi+pj), i-pi)
            dp0 += tmp * solve(ind2)[1] % MOD
            dp1 += tmp * solve(ind2)[0] % MOD
    dp[ind] = (dp0, dp1)
    return dp[ind]

for i in range(n):
    solve(i)
print((dp[n-1][0] - dp[n-1][1]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
class Combination:
    '''MOD上の
    計算量：階乗・逆元テーブルの作成O(N)
    nCkを求めるO(1)'''

    def __init__(self, n, MOD):
        self.fact = [1] * (n + 1)
        for i in range(1, n + 1):
            self.fact[i] = self.fact[i-1] * i % MOD
        self.inv_fact = [pow(self.fact[i], MOD - 2, MOD) for i in range(n + 1)]
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


h, w, n = map(int, input().split())
info = [(1, 1)] + [tuple(map(int, input().split())) for i in range(n)] + [(h, w)]
n += 2
MOD = 10**9 + 7
comb = Combination(w+h+1, MOD)

dp = {}
dp[0] = (0, 1)
def solve(ind):
    if ind in dp:
        return dp[ind]
    i, j = info[ind]
    dp0 = 0
    dp1 = 0
    for ind2 in range(n):
        if ind2 == ind:
            continue
        pi, pj = info[ind2]
        if pi <= i and pj <= j:
            dp0 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[1]
            dp1 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[0]
            dp0 %= MOD
            dp1 %= MOD
    dp[ind] = (dp0, dp1)
    return dp[ind]

for i in range(n):
    solve(i)
print((dp[n-1][0] - dp[n-1][1]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
class Combination:
    '''MOD上の
    計算量：階乗・逆元テーブルの作成O(N)
    nCkを求めるO(1)'''

    def __init__(self, n, MOD):
        self.fact = [1]
        for i in range(1, n + 1):
            self.fact.append(self.fact[-1] * i % MOD)
        self.inv_fact = [pow(self.fact[i], MOD - 2, MOD) for i in range(n + 1)]
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


h, w, n = map(int, input().split())
info = [(1, 1)] + [tuple(map(int, input().split())) for i in range(n)] + [(h, w)]
n += 2
MOD = 10**9 + 7
comb = Combination(w+h+1, MOD)

dp = {}
dp[0] = (0, 1)
def solve(ind):
    if ind in dp:
        return dp[ind]
    i, j = info[ind]
    dp0 = 0
    dp1 = 0
    for ind2 in range(n):
        if ind2 == ind:
            continue
        pi, pj = info[ind2]
        if pi <= i and pj <= j:
            dp0 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[1]
            dp1 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[0]
            dp0 %= MOD
            dp1 %= MOD
    dp[ind] = (dp0, dp1)
    return dp[ind]

for i in range(n):
    solve(i)
all_ptn = comb.combination((w-1+h-1), h-1)
print((dp[n-1][0] - dp[n-1][1]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
class Combination:
    '''MOD上の
    計算量：階乗・逆元テーブルの作成O(N)
    nCkを求めるO(1)'''

    def __init__(self, n, MOD):
        self.fact = [1]
        for i in range(1, n + 1):
            self.fact.append(self.fact[-1] * i % MOD)
        self.inv_fact = [pow(self.fact[i], MOD - 2, MOD) for i in range(n + 1)]
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


h, w, n = map(int, input().split())
info = [[1, 1]] + [list(map(int, input().split())) for i in range(n)] + [[h, w]]
n += 2
MOD = 10**9 + 7
comb = Combination(w+h+1, MOD)

dp = [[-1]*n for _ in range(2)]
dp[1][0] = 1
dp[0][0] = 0
def solve(ind):
    if dp[0][ind] != -1:
        return dp[0][ind], dp[1][ind]
    i, j = info[ind]
    dp0 = 0
    dp1 = 0
    for ind2 in range(n):
        if ind2 == ind:
            continue
        pi, pj = info[ind2]
        if pi <= i and pj <= j:
            dp0 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[1]
            dp1 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[0]
            dp0 %= MOD
            dp1 %= MOD
    dp[0][ind] = dp0
    dp[1][ind] = dp1
    return dp[0][ind], dp[1][ind]

for i in range(n):
    solve(i)
all_ptn = comb.combination((w-1+h-1), h-1)
print((dp[0][n-1] - dp[1][n-1]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
class Combination:
    '''MOD上の
    計算量：階乗・逆元テーブルの作成O(N)
    nCkを求めるO(1)'''

    def __init__(self, n, MOD):
        self.fact = [1]
        for i in range(1, n + 1):
            self.fact.append(self.fact[-1] * i % MOD)
        self.inv_fact = [pow(self.fact[i], MOD - 2, MOD) for i in range(n + 1)]
        self.MOD = MOD

    def factorial(self, k):
        """k!を求める O(1)"""
        return self.fact[k]

    def inverse_factorial(self, k):
        """k!の逆元を求める O(1)"""
        return self.inv_fact[k]

    def permutation(self, k, r):
        """kPrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[r]) % self.MOD

    def combination(self, k, r):
        """kCrを求める O(1)"""
        if k < r:
            return 0
        return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD


h, w, n = map(int, input().split())
info = [[1, 1]] + [list(map(int, input().split())) for i in range(n)] + [[h, w]]
n += 2
MOD = 10**9 + 7
comb = Combination(w+h+1, MOD)

dp = [[-1]*2 for _ in range(n)]
dp[0][1] = 1
dp[0][0] = 0
def solve(ind):
    if dp[ind][0] != -1:
        return dp[ind]
    i, j = info[ind]
    dp0 = 0
    dp1 = 0
    for ind2 in range(n):
        if ind2 == ind:
            continue
        pi, pj = info[ind2]
        if pi <= i and pj <= j:
            dp0 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[1]
            dp1 += comb.combination((i+j)-(pi+pj), i-pi) * solve(ind2)[0]
            dp0 %= MOD
            dp1 %= MOD
    dp[ind][0] = dp0
    dp[ind][1] = dp1
    return dp[ind]

for i in range(n):
    solve(i)
all_ptn = comb.combination((w-1+h-1), h-1)
print((dp[n-1][0]- dp[n-1][1]) % MOD)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def com(com_n, com_r):
    return fac[com_n] * inv[com_r] * inv[com_n - com_r] % md
def way(h, w):
    if h < 0 or w < 0:
        return 0
    else:
        return com(h + w, h)

# combinationの準備
# md>n_maxの条件
md = 10 ** 9 + 7
n_max = 200005
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
    k_fac_inv = k_fac_inv * i % md
    fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
    inv[i] = k_fac_inv
    k_fac_inv = k_fac_inv * i % md

def main():
    h, w, n = MI()
    rc = [LI1() for _ in range(n)]
    # i番目の壁まで無傷で来る方法の数
    # (全ルート)－(i-1までの壁にぶつかる分)
    rc.sort(key=lambda x: x[0] + x[1])
    dp = [0] * n
    for i, (r, c) in enumerate(rc):
        dp[i] = way(r, c) - sum(v * way(r - pr, c - pc) % md for v, (pr, pc) in zip(dp[:i], rc[:i]))
        dp[i] %= md
    h, w = h - 1, w - 1
    ans = way(h, w) - sum(v * way(h - r, w - c) % md for v, (r, c) in zip(dp, rc))
    print(ans % md)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
h, w, n = [int(i) for i in sys.stdin.readline().split()]
m = 1000000007
fact = [1, 1]
for i in range(2, 200002):
    fact.append(fact[-1] * i)
inv = [pow(i, m - 2, m) for i in fact]
f = lambda i: fact[i[0] + i[1]] * inv[i[0]] * inv[i[1]] % m
dp = [0] * (n + 1)
p = [[int(i) - 1 for i in sys.stdin.readline().split()] for j in range(n)]
p = sorted(p + [[h - 1, w - 1]])
for i in range(n + 1):
    h1, w1 = p[i]
    tot = f([h1, w1])
    for j in range(i):
        if p[j][1] > w1:
            continue
        tot = (tot - dp[j] * f([h1 - p[j][0], w1 - p[j][1]]) % m) % m
    dp[i] = tot
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
h, w, n = [int(i) for i in input().split(" ")]
m = 1000000007
fact = [1, 1]
for i in range(2, 250000):
    fact.append(fact[-1] * i)
inv = [pow(i, m - 2, m) for i in fact]
f = lambda i: fact[i[0] + i[1]] * inv[i[0]] * inv[i[1]] % m
dp = [0] * (n + 1)
p = [[int(i) - 1 for i in input().split(" ")] for j in range(n)]
p = sorted(p + [[h - 1, w - 1]])
for i in range(n + 1):
    h1, w1 = p[i]
    tot = f([h1, w1])
    for j in range(i):
        if p[j][1] > w1:
            continue
        tot = (tot - dp[j] * f([h1 - p[j][0], w1 - p[j][1]]) % m) % m
    dp[i] = tot
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def modfact(n):
    fact=[1]*(n+1)
    invfact=[1]*(n+1)
    for i in range(1,n+1):
        fact[i]=i*fact[i-1]%MOD
    invfact[n]=pow(fact[n],MOD-2,MOD)
    for i in range(n-1,-1,-1):
        invfact[i]=invfact[i+1]*(i+1)%MOD
    return fact,invfact

def resolve():
    h,w,n=map(int,input().split())
    R=[(1,1),(h,w)]+[tuple(map(int,input().split())) for _ in range(n)]
    R.sort()
    n+=1
    dp=[[0]*2 for _ in range(n+1)]
    dp[0][0]=1
    fact,invfact=modfact(200000)
    for i in range(n):
        x,y=R[i]
        for j in range(i+1,n+1):
            dx=R[j][0]-x
            dy=R[j][1]-y
            if(dx<0 or dy<0): continue
            for m in range(2):
                dp[j][1-m]+=dp[i][m]*fact[dx+dy]*invfact[dx]*invfact[dy]
                dp[j][1-m]%=MOD
    print((dp[n][1]-dp[n][0])%MOD)
resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    from math import factorial
    h,w,n=map(int,input().split())
    R=[(1,1),(h,w)]+[tuple(map(int,input().split())) for _ in range(n)]
    R.sort()
    n+=1
    dp=[[0]*2 for _ in range(n+1)]
    dp[0][0]=1
    for i in range(n):
        x,y=R[i]
        for j in range(i+1,n+1):
            dx=R[j][0]-x
            dy=R[j][1]-y
            if(dx<0 or dy<0): continue
            for m in range(2):
                dp[j][1-m]+=dp[i][m]*factorial(dx+dy)//factorial(dx)//factorial(dy)
                dp[j][1-m]%=MOD
    print(dp[n][1]-dp[n][0])
resolve()

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/dp/tasks/dp_h

h, w, n = [int(i) for i in raw_input().split()]
walls = []

for i in xrange(n):
    i, j = [int(i) for i in raw_input().split()]
    walls.append((i-1,j-1))
walls.append((h-1, w-1))

walls.sort()

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def binomial(n, k):
    # n choose k mod p
    # (n, k) mod m = (n! * (k!)^-1 * ((n - k)!)^-1) mod m

    p = int(1e9) + 7
    first = 1
    for x in range(1, n+1):
        first = first * x % p

    second = 1
    for x in range(1, k+1):
        second = second * x % p

    third = 1
    for x in range(1, n-k+1):
        third = third * x % p

    output = first * modinv(second, p) * modinv(third, p) % p

    return output

f = [0] * len(walls) # ways to reach dest without going through f[i]

# print walls

for i in range(len(walls)):
    f[i] = binomial(walls[i][0]+walls[i][1], walls[i][0])

# print f

# f[i] = no of ways to reach (h,w) without going walls[0..i]

p = int(1e9+7)
for i in range(len(walls)):
    for j in range(i+1, len(walls)):
        if walls[j][0] >= walls[i][0] and walls[j][1] >= walls[i][1]:
            f[j] -= f[i] * binomial(walls[j][0]-walls[i][0]+walls[j][1]-walls[i][1], walls[j][0]-walls[i][0])
            f[j] %= p

# print f
print f[-1] % (int(1e9)+7)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/dp/tasks/dp_h

h, w, n = [int(i) for i in raw_input().split()]
walls = []

for i in xrange(n):
    i, j = [int(i) for i in raw_input().split()]
    walls.append((i-1,j-1))
walls.append((h-1, w-1))

walls.sort()

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def binomial(n, k):
    # n choose k mod p
    # (n, k) mod m = (n! * (k!)^-1 * ((n - k)!)^-1) mod m

    p = int(1e9) + 7
    first = 1
    for x in range(1, n+1):
        first = first * x % p

    second = 1
    for x in range(1, k+1):
        second = second * x % p

    third = 1
    for x in range(1, n-k+1):
        third = third * x % p

    output = first * modinv(second, p) * modinv(third, p) % p

    return output

f = [0] * len(walls) # ways to reach dest without going through f[i]

# print walls

for i in range(len(walls)):
    f[i] =  binomial(walls[i][0]+walls[i][1], walls[i][0])

# print f

# f[i] = no of ways to reach (h,w) without going walls[0..i]

for i in range(len(walls)):
    for j in range(i+1, len(walls)):
        if walls[j][0] >= walls[i][0] and walls[j][1] >= walls[i][1]:
            f[j] -= f[i] * binomial(walls[j][0]-walls[i][0]+walls[j][1]-walls[i][1], walls[j][0]-walls[i][0])

# print f
print f[-1] % (int(1e9)+7)