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.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to compute number of lattice paths from (1,1) to (h,w) moving only down or right, avoiding certain black cells. Constraints: h,w up to 1e5, but number of black cells n <= 2000. So we need to compute total number of paths without restrictions minus those that go through black cells, but inclusion-exclusion over black cells is tricky because they can block each other. Standard approach: sort black cells in order (increasing row then column) and use DP to count paths from start to each black cell avoiding other black cells, then compute number of ways from each black cell to end, then total paths that go through at least one black cell using DP with inclusion-exclusion via "bad" cells ordering.
Alternatively, compute total number of paths from (1,1) to (h,w) = C(h+w-2, h-1) (since need h-1 downs and w-1 rights). Then we need to subtract paths that pass through any black cell. Since n small, we can use DP with sorting: Let the black cells be points P1,...,Pn. Add start as (1,1) and end as (h,w). Compute number of paths from start to each point without passing through any black point earlier in the sorted order. Then number of paths from start to end that avoid all black points is total paths from start to end minus sum_{i} (paths from start to Pi * paths from Pi to end) but need inclusion-exclusion for overlapping. Instead, we do:
Define points sorted by (r,c) ascending. Let dp[i] = number of ways to reach point i from start (1,1) without passing through any other black point (excluding start and maybe other black points). Compute dp[i] = total ways from start to Pi - sum_{j < i and Pj is before Pi} dp[j] * ways(Pj -> Pi). This ensures that we only count paths that first hit a black point at Pi. Then total number of paths that go through any black point is sum_{i} dp[i] * ways(Pi -> end). Then answer = total - that sum (mod MOD). But careful: we also need to ensure start and end are white. Since we are subtracting paths that hit any black point, we want answer = number of paths avoiding all black cells. So we compute total, then subtract sum over i of (number of paths that first black point is Pi) * ways(Pi to end). That works.
Thus we need to compute ways(A -> B) for any two points A=(r1,c1), B=(r2,c2) with r1 <= r2, c1 <= c2, assuming no restrictions (but if there are black cells in between, we are computing raw binomial count). Since we will only use this for pairs where A and B are among black cells sorted, we compute binomial coefficient: number of paths from (r1,c1) to (r2,c2) is C((r2-r1)+(c2-c1), r2-r1). Since moves only down/right.
Thus we need to precompute factorials and inverse factorials up to max coordinate sum: h+w up to 2e5, because h,w <= 1e5, so max (h-1)+(w-1) = h+w-2 <= 2e5 - 2, but also we need to compute binomials for differences that are up to h+w. Actually we need factorial up to (h+w) maybe because (r2-r1)+(c2-c1) max is (h-1)+(w-1) = h+w-2, but if we compute from (1,1) to (h,w) it's h-1 + w-1 = h+w-2. So we need factorial up to 200000 (since h+w <= 200000). Let's set N = 200010 maybe.
But careful: h and w up to 1e5, so h+w can be up to 200000. So precomputing factorial up to 200000 is fine.
Now implement:
MOD = 10^9+7.
Read h,w,n.
Store black cells as list of (r,c).
Add start? Not needed; we will treat start separately. Actually in DP, we need to compute dp for each black cell as "first black encountered". So we sort black cells. Then we can compute dp[i] for i from 0 to n-1.
Define function ways(r1,c1,r2,c2) if r1<=r2 and c1<=c2 else 0. Compute dx = r2-r1, dy = c2-c1, return C(dx+dy, dx).
Since we want paths that go from start to Pi without passing any other black cell. This is standard.
But careful: dp[i] should count all paths from start to Pi that avoid all black cells except possibly Pi (i.e., they may pass through Pi, and no black cell before Pi). Since we want first black cell to be Pi. That's exactly what we compute.
But note that the start is white; Pi is black, so we want to count paths that go through Pi (and possibly also through other black cells later, but we only count those where Pi is the first black encountered). So dp[i] is the number of paths that hit a black cell first at Pi.
Then the total number of paths that go through at least one black cell = sum_i dp[i] * ways(Pi -> end). Because for any path that hits at least one black, let the first black encountered be Pi, then from Pi to end it can be any path (including other black cells, because we are counting the whole path; but we are counting each path exactly once if we condition on the first black encountered). However careful: If the path passes through multiple black cells, we count it exactly once for the first black encountered. So sum_i (dp[i] * ways(Pi -> end)) counts exactly all paths that contain at least one black cell. But we must ensure that the path from Pi to end is allowed to pass through other black cells? Actually if the path from Pi to end passes through another black cell, then the first black encountered remains Pi, and the path will be counted in dp[i] * ways(Pi -> end) only if ways(Pi -> end) counts all paths from Pi to end regardless of black cells. However dp[i] ensures that before Pi there are no black cells. The path from Pi to end might go through other black cells, but that's fine; the overall path still has at least one black cell. So that count yields exactly the number of paths that pass through at least one black cell? Wait, is there any double counting? Suppose a path passes through black cells at positions Pi and Pj (with Pi encountered first). Then it will be counted exactly in dp[i] * ways(Pi->end) because among all paths from Pi to end, there will be one that goes through Pj as well. But is it possible that the same path might also be counted for dp[j] * ways(Pj->end)? No, because for dp[j] we require that no black cell before Pj is encountered; but since Pi is before Pj, such a path would have Pi before Pj, so it would not satisfy that condition. So each path is counted exactly once for its first black cell. So total bad paths = sum_i dp[i] * ways(Pi->end). Good.
But we need to be careful: The path from Pi to end computed as ways(Pi -> end) may go through black cells, but we are including those. That's correct for counting bad paths.
Thus answer = (total - sum_i dp[i]*ways(Pi->end)) mod MOD.
But wait: Is it possible that a path from start to end avoids all black cells? That's the answer we want. So yes.
But double-check: start and end are white, so dp for start not needed.
Now edge case: Black cells list may contain cells that are unreachable from start because you would need to go left/up? But since we only move down/right, a black cell (r,c) is reachable from start if r>=1 and c>=1, obviously; but also from start to Pi, we need r>=1,c>=1 always true. But what if some black cell is located such that there is no path from start to it without passing through another black cell? That's fine; dp[i] will be computed accordingly.
Now need to handle modulo arithmetic: compute factorials and inv factorials up to limit = h+w (maybe 200000). Actually max needed binomial argument: (dx+dy) where dx = r2 - r1, dy = c2 - c1. The maximum possible dx+dy is from (1,1) to (h,w) = h-1 + w-1 = h+w-2. So we need up to h+w-2. Also we might compute from (1,1) to a black cell and from black to end, all within that range. So let maxN = h + w (or 200000). Use precomputation.
Complexities: O(n^2) because for each i we sum over j < i, n <= 2000, so 4 million operations, fine.
Implementation steps:
Read h, w, n.
black = []
For each n: read r,c; append (r, c).
Sort black by (r, c) (row then column).
Precompute factorial and inv factorial up to maxN = h + w + 5 (to be safe). Actually (h+w) maybe 200000, so we can set MAX = 200010 or compute dynamically: maxN = h + w.
Define comb(n, k) returning 0 if k<0 or k>n else fact[n]*invfact[k]%mod * invfact[n-k]%mod.
Define ways(r1,c1,r2,c2): if r1>r2 or c1>c2: return 0; else return comb(r2-r1 + c2-c1, r2-r1).
total = ways(1,1,h,w)
Initialize dp array of size n (maybe using list). Also maybe compute all startToBlack[i] = ways(1,1, r_i, c_i) for each i.
For i in range(n):
dp[i] = startToBlack[i]
for j in range(i):
if r_j <= r_i and c_j <= c_i: (since ways is zero otherwise; but given sorting, if sorted by row then column, we might have r_j <= r_i, but not necessarily c_j <= c_i; because sorting by row first, if rows equal, then columns increasing, so c_j <= c_i when rows equal; but if r_j < r_i, it's possible that c_j > c_i, then paths from Pj to Pi may be impossible because need to go down and right, but c_j > c_i would require left moves. So we must check condition: r_j <= r_i and c_j <= c_i. So we only subtract for those j that are "before" Pi in the partial order (i.e., reachable from Pi by moving down/right). So if condition holds, subtract dp[j]ways(r_j,c_j, r_i,c_i) mod.
dp[i] = (dp[i] - sum_j dp[j]...) % mod. Ensure non-negative.
Compute bad = 0
For each i: bad += dp[i] * ways(r_i,c_i, h,w) % mod.
ans = (total - bad) % MOD
If ans < 0, add MOD.
print ans.
Check examples:
Example 1:
h=3,w=4, n=2: black (2,2),(2,3). Sorted: (2,2),(2,3).
Compute total: from (1,1) to (3,4): need 2 down, 3 right => C(5,2)=10? Actually 2 down, 3 right => total moves=5, choose 2 down => 10. So total=10.
Now dp[0] for (2,2): start to (2,2) = ways(1,1,2,2) = C( (1+1),1 )? Actually dx=1, dy=1 => total 2 choose 1 =2. So dp0=2.
dp[1] for (2,3): start to (2,3)= ways(1,1,2,3) dx=1, dy=2 => C(3,1)=3. Then subtract dp0 * ways((2,2)->(2,3)) = 2 * ways(2,2,2,3) = 2 * C(1,0) because dx=0, dy=1 => C(1,0)=1? Wait: (2,2)->(2,3): dx=0, dy=1 => C(1,0)=1. So subtract 21=2 => dp1 = 3-2=1.
Now bad = dp0ways((2,2)->(3,4)) + dp1ways((2,3)->(3,4)).
Ways(2,2->3,4): dx=1, dy=2 => C(3,1)=3 => dp03=23=6.
Ways(2,3->3,4): dx=1, dy=1 => C(2,1)=2 => dp12=1*2=2.
Bad total = 8.
Ans = 10-8=2. Matches example.
Example 2:
h=100,w=100,n=3, cells: (15,16),(16,15),(99,88). Let's compute using code later, expected 545732279.
Thus algorithm should be correct.
But we need to be careful about modulo negative.
Also note that dp[i] can be zero if all paths to that black cell are blocked by earlier black cells.
Potential pitfalls: Sorting order must respect reachability: if we sort by (r,c) ascending, does that guarantee that if Pj can reach Pi (i.e., r_j<=r_i and c_j<=c_i) then j < i? Not necessarily: consider (2,3) and (3,2). Sorted by row then column: (2,3) then (3,2). Here r_j=2 <= r_i=3, but c_j=3 > c_i=2, so (2,3) cannot reach (3,2) because need to move right? Actually from (2,3) to (3,2): need to go down and left, but left is not allowed. So it's unreachable. So we only subtract for those j where c_j <= c_i, and since sorting by row then column, for rows less, we might have columns that are larger, making unreachable. So we need to check condition. That's fine.
But what if two black cells have same row but different columns, sorted ascending columns, then for j<i, we have same row so c_j < c_i, so reachable (dx=0, dy positive). That's fine.
If two black cells have same column but different rows, sorted by row first, so j<i implies r_j < r_i, same column => c_j = c_i, then reachable (dx positive, dy=0). So condition holds.
So sorting by (r,c) ensures that for reachable j, j will appear before i if both r and c are less or equal? Actually consider (3,2) and (2,3). Sorted by row: (2,3) then (3,2). Here (2,3) is before (3,2). But can (2,3) reach (3,2)? No. So we don't need to subtract. That's okay because we check condition.
Now what about a black cell that is reachable from another black cell but j appears after i in sorting order? Could that happen? Suppose Pi = (2,2), Pj = (3,1). Sorted by row: (2,2) then (3,1). Here Pi is before Pj. For Pi to reach Pj, need c_i <= c_j? 2 <= 1? false, so not reachable. So okay.
Consider (2,5) and (3,4). Sorted: (2,5) then (3,4). Check reachable: r2<=r3 (true), c5<=c4 false => not reachable. So it's fine.
Consider (4,1) and (3,2). Sorted: (3,2) then (4,1) because row 3 < 4. But can (3,2) reach (4,1)? c2 <=1? false. Not reachable. So fine.
Now consider (3,3) and (4,2). Sorted: (3,3) before (4,2). Not reachable. So condition handles.
Thus sorting by (r,c) is acceptable, and we just need to check both coordinates.
Alternative: sort by (r+c) or something, but current is fine.
Now we must compute factorials up to maxN. But note: h and w can be up to 1e5, but we need factorial up to h+w which could be up to 200,000. That's fine.
Potential overflow in intermediate multiplication? Python handles big ints, but we use mod.
Now check if we need to handle the case where there are duplicate black cells? The problem says all cells are distinct, so fine.
Now complexity: O(n^2) ~4 million, each operation involves a constant number of modular multiplications and binomial lookups (O(1) after precomputation). So fine.
But careful: ways(r_j,c_j,r_i,c_i) may be zero if condition fails, we can skip.
Now test with example 2 manually? Not needed.
Edge Cases:
n = 0: Then dp array empty, bad=0, answer = total. Should work.
Some black cells not reachable from start? Actually from start (1,1) to (r,c) is always reachable because r>=1, c>=1 and we only go down/right, so always reachable (since we can always increase row and column). Actually if r < 1 or c < 1 would be impossible but that's not possible. So all black cells are reachable from start (as long as they are not before start). But note: start itself is white, so black cells could be at (1,1) or (h,w) but problem guarantees upper left and lower right are white. So no black at start or end. So all black are reachable.
Some black cells may be unreachable from another black cell due to coordinate constraints, that's fine.
Now confirm that our DP for dp[i] indeed yields number of paths from start to Pi that avoid all other black cells. The recurrence: dp[i] = all paths to Pi minus sum over earlier black cells j (that are reachable from start and to Pi) of paths that go through j first then to Pi, where dp[j] counts paths that hit j first and avoid others. So subtraction removes those that pass through any earlier black cell. This works because any path from start to Pi that passes through some black cell must have a first black cell, which will be some j with j < i (since if j is reachable from start to Pi, and it appears before i in the sorted order? Need to ensure that if a path passes through black cell j that is not comparable in sorting order? But we argued that if j is reachable from start and also reachable to Pi, then it must be that r_j <= r_i and c_j <= c_i (since path from start to j and from j to Pi exist). That implies that j is before i in sorted order? Not necessarily: sorting by row then column, if r_j < r_i, then j appears before i regardless of columns. If r_j = r_i, then c_j < c_i for reachability (since need c_j <= c_i, but if equal, it's same cell, but they are distinct so c_j < c_i). So j will be before i. If r_j > r_i, then j would be after i in sorted order, but then from j to Pi would require r_j <= r_i, contradiction. So indeed any j that is reachable from start and can reach Pi will satisfy r_j <= r_i and c_j <= c_i, and thus in sorting by row then column, j will be before i because either r_j < r_i or (r_j == r_i and c_j < c_i). So j < i. So the recurrence is valid.
Thus DP correct.
Now we need to compute factorial and inverse factorial modulo MOD = 1e9+7.
We'll precompute up to maxN = h + w (maybe add extra 5). Actually the maximum n in binomial we need is (h-1)+(w-1) = h+w-2. So maxN = h+w is enough. But we also need to compute comb for numbers like (r2-r1)+(c2-c1) which can be less than that. So set N = h + w + 5.
Implementation details:
Use pow(x, MOD-2, MOD) for modular inverse.
Precompute fact[0..N] and invfact similarly.
Now let's code.
But also note that if the answer is negative after subtraction, we can do ans %= MOD.
Now test with sample.
Potential pitfalls: if we compute dp[i] and subtract many contributions, we might get negative; we can mod and then add MOD if needed.
Also note that dp[i] may be needed for later j.
Now let's write code.
Edge case: It might be that some black cell is not reachable from start? Already discussed reachable.
Now we should be careful with indexing: rows and columns from 1 to h, w.
Now verify with example 2 using Python quickly (simulate mental? not needed).
Now we can finalize.
But wait, there is another nuance: The DP for dp[i] uses all paths from start to Pi, but includes paths that go through black cells that are not in the list? Actually all black cells are listed, so any path that goes through a black cell must go through some of them. So subtraction via dp[j] for j < i removes those where the first black is some j. So dp[i] ends up counting paths that avoid all black cells before Pi (i.e., avoid all black cells in the set except possibly Pi). So it's fine.
Now answer = total - sum(dp[i] * ways(Pi -> end)). Since dp[i] counts paths that first hit black at Pi, and from Pi to end we count all paths (including hitting other black cells). So total bad counted once.
Thus answer correct.
Now complexity O(n^2) with n=2000, should be fine.
But we must also consider that h,w up to 1e5, so precomputing factorial up to 200000 is fine.
Now final step: code.
But also consider memory: factorial arrays of size 200001 ~ OK.
Now let's implement.
Pseudo:
MOD = 1000000007
def precompute_fact(limit):
fact = [1]*(limit+1)
for i in range(1, limit+1):
fact[i] = fact[i-1]i % MOD
inv_fact = [1](limit+1)
inv_fact[limit] = pow(fact[limit], MOD-2, MOD)
for i in range(limit, 0, -1):
inv_fact[i-1] = inv_fact[i]*i % MOD
return fact, inv_fact
def comb(n, k, fact, inv_fact):
if k < 0 or k > n:
return 0
return fact[n] * inv_fact[k] % MOD * inv_fact[n-k] % MOD
def ways(r1,c1,r2,c2):
if r1 > r2 or c1 > c2:
return 0
dx = r2 - r1
dy = c2 - c1
return comb(dx+dy, dx, fact, inv_fact)
Then main:
import sys
input data.
h,w,n = map(int, sys.stdin.readline().split())
black = []
for _ in range(n):
r,c = map(int, sys.stdin.readline().split())
black.append((r,c))
black.sort() # sorts by row then column
limit = h + w # maybe plus 5
fact, inv_fact = precompute_fact(limit)
total = ways(1,1,h,w)
precompute start_to_black[i] maybe
start_to_black = [ways(1,1,r,c) for (r,c) in black]
n = len(black)
dp = [0]*n
for i in range(n):
r_i, c_i = black[i]
val = start_to_black[i]
for j in range(i):
r_j, c_j = black[j]
if r_j <= r_i and c_j <= c_i:
val -= dp[j] * ways(r_j, c_j, r_i, c_i) % MOD
dp[i] = val % MOD
bad = 0
for i in range(n):
r_i, c_i = black[i]
bad = (bad + dp[i] * ways(r_i, c_i, h, w)) % MOD
ans = (total - bad) % MOD
if ans < 0:
ans += MOD
print(ans)
Now test with sample.
We'll simulate in Python mental or by writing but let's check for potential off-by-one errors: In ways, we use dx = r2 - r1, dy = c2 - c1, and comb(dx+dy, dx). That's correct because we need to make (dx+dy) moves, choose which are down moves.
Now for total: (1,1) to (h,w) => dx = h-1, dy = w-1 => comb(h-1 + w-1, h-1) = comb(h+w-2, h-1). That's the standard.
Now for start_to_black: from (1,1) to (r,c) => dx = r-1, dy = c-1 => comb(r-1 + c-1, r-1) = comb(r+c-2, r-1). Good.
Now for black to black: from (r_j,c_j) to (r_i,c_i) => dx = r_i - r_j, dy = c_i - c_j.
Now for black to end: from (r_i,c_i) to (h,w) => dx = h - r_i, dy = w - c_i.
Now all within limits.
Now check example 2 using code? Let's approximate quickly (but trust code).
Edge Cases:
If a black cell is not reachable from start because it's above or left? Not possible.
If a black cell is (1,2) then start_to_black: from (1,1) to (1,2) => dx=0, dy=1 => comb(1,0)=1. That's fine.
Now one more nuance: The DP for dp[i] subtracts sum_{j < i} dp[j]*ways(Pj->Pi). However, this subtracts contributions where the path goes from start to Pj (first black) and then to Pi (maybe passing other black cells? But dp[j] counts paths that have first black at Pj, meaning before Pj there are no blacks. The segment from Pj to Pi might pass through other black cells. However, those paths would be counted in dp[i] as paths that have first black at Pi? Actually if the segment from Pj to Pi passes through another black cell Pk (with j < k < i), then the overall path has first black at Pj, not at Pi. So we should not subtract such paths from dp[i] via dp[j]*ways(Pj->Pi) because those paths are not counted in dp[i] in the first place (they are removed by subtraction for Pk? Wait, careful: In the computation of dp[i] as total paths to Pi minus sum_{j} dp[j]*ways(Pj->Pi), we consider all j < i. Among those j, we include j that are reachable to Pi. For a path that goes from start to Pj (first black), then to Pi, and along the way from Pj to Pi, it passes through Pk (where j<k<i), that path is still a valid path from start to Pi that has a first black at Pj. However, does our subtraction correctly remove it? We subtract dp[j]*ways(Pj->Pi). That product counts all paths from Pj to Pi, including those that go through other black cells (like Pk). So indeed we subtract that path. But then, after subtraction, dp[i] counts only paths that have first black at Pi. That's correct. However, note that we also have dp[k] computed for Pk, and we also subtract dp[k]*ways(Pk->Pi) later when computing dp[i]. But the path that goes start->Pj->...->Pk->...->Pi would be subtracted both via dp[j] and dp[k] if we are not careful? Actually dp[j]*ways(Pj->Pi) includes those that go through Pk. dp[k]*ways(Pk->Pi) includes those that go from start to Pk (first black) and then to Pi. But the same path might be counted twice if we subtract both? However, our expression dp[i] = total - sum_{j} dp[j]*ways(Pj->Pi) is meant to subtract all paths that have any black before Pi, counting each exactly once. But if we subtract both contributions for the same path, we would over-subtract. That would be problematic. So we must ensure that for any path from start to Pi that has first black at some j, it is subtracted exactly once, via the term for that j. However, our sum over j includes all j that are reachable and before i. But a path that first hits black at j, and later passes through k (where j < k < i) on the way to Pi, will be included in the term dp[j]*ways(Pj->Pi). It will also be included in dp[k]*ways(Pk->Pi) only if the path's first black is k, but it is not because first black is j. So dp[k] does not count that path because dp[k] counts only paths whose first black is exactly k. So the path in question is not counted in dp[k] because before reaching k, it already passed through j which is black, so the path is not a valid first-black-at-k path. Therefore, it is not subtracted in dp[k]*ways(Pk->Pi). So no double counting. Good.
Now what about paths that have first black at j, but the segment from j to Pi avoids all other black cells? That's fine, they are subtracted once via j.
Now what about paths that have first black at j, but the segment from j to Pi goes through some black cell k that appears after j but before i; but as argued, that path is still counted in dp[j]*ways(Pj->Pi) because ways(Pj->Pi) counts all paths from j to Pi, regardless of intermediate black cells. So subtracted once. And it is not counted in dp[k]*ways(Pk->Pi) because dp[k] does not include that path (first black is j, not k). So correct.
Thus recurrence works.
Now check that we are not missing paths that go through multiple black cells but the first black appears after i in sorted order? Not possible because first black must be reachable and appear before i if it can reach Pi? As argued earlier, if j is first black and also can reach Pi, then r_j <= r_i and c_j <= c_i. Under sorting by row then column, this ensures j < i. So yes.
Now we also need to consider if there are black cells that are not comparable (i.e., one not reachable from the other). Then a path that goes from start to Pi may pass through j only if j is reachable from start and from j to Pi is possible; that requires comparability. So if not comparable, it can't be that j is on a path to Pi. So we only subtract for comparable j.
Now everything is fine.
Now let's test with a small scenario to further validate:
Suppose h=2,w=2, board 2x2, only black cell at (1,2). Then total paths from (1,1) to (2,2): need one down and one right; two possible sequences: right then down, down then right. But (1,2) is black, so path "right then down" is invalid. So answer = 1.
Our algorithm: black = [(1,2)] sorted. total = ways(1,1,2,2) = C(2,1)=2. dp[0] = ways(1,1,1,2) = C(1,0)=1 (only right). Since no earlier j, dp[0]=1. Then bad = dp[0]ways(1,2,2,2)=1 ways(1,2->2,2)= C(1,1)=1? Actually dx=1,dy=0 => C(1,1)=1, so bad=1. ans=2-1=1. Good.
Suppose black at (2,1). Similarly answer=1.
Suppose black at (1,2) and (2,1). Total=2. Both black. The only valid path would be? To avoid both black, you cannot go right first (hits (1,2)) nor down first (hits (2,1)). So answer=0. Black cells: sorted: (1,2) then (2,1). dp[0] = ways(1,1,1,2)=1. dp[1] = ways(1,1,2,1)=1 (down). Subtract for j=0: need check if (1,2) can reach (2,1)? r1=1<=2, c2=2<=1 false, so no subtract. So dp[1]=1. Then bad = dp0ways((1,2)->(2,2)) =11 (right? Actually (1,2)->(2,2) dx=1,dy=0 =>1) =1; plus dp1ways((2,1)->(2,2)) =11 (right? (2,1)->(2,2) dx=0,dy=1 =>1)=1. So bad=2. ans=0. Good.
Now scenario where a black cell is after another but still reachable: e.g., black at (2,2) and (2,3). Already example.
Now scenario where a black cell is after another but not reachable, we already considered.
Now scenario where multiple blacks on same path: e.g., h=3,w=3, black at (1,2) and (2,3). Sorted: (1,2), (2,3). total paths from (1,1) to (3,3): need 2 down,2 right => C(4,2)=6. List all paths (RRDD, RDRD, RDDR, DRRD, DRDR, DDRR). Black (1,2) is after moving right first; black (2,3) could be hit after sequence? Let's enumerate:
RRDD: moves: (1,1)->(1,2) R -> black; (1,2)->(1,3) R; then down,down. So hits (1,2) first.
RDRD: (1,1)->(1,2)R (black); then D to (2,2); then R to (2,3)? That's black (2,3); but first black (1,2) so hits.
RDDR: (1,1)->(1,2)R (black); then D to (2,2); then D to (3,2); then R to (3,3). Hits (1,2).
DRRD: D to (2,1); R to (2,2); R to (2,3) - black (2,3); then D to (3,3). First black is (2,3).
DRDR: D to (2,1); R to (2,2); D to (3,2); R to (3,3). This does not hit (2,3) because after D then R, but at (2,2) then D to (3,2) bypasses (2,3). So avoids both? Check (2,3) is not visited. Also (1,2) not visited. So valid.
DDRR: D to (2,1); D to (3,1); R to (3,2); R to (3,3). Avoids both. So valid.
Thus valid paths: DRDR and DDRR, so answer=2.
Our algorithm: black = [(1,2),(2,3)]. total=6.
dp0 = ways(1,1,1,2) = C(1,0)=1.
dp1 = ways(1,1,2,3) = need dx=1,dy=2 => C(3,1)=3? Actually from (1,1) to (2,3): down 1, right 2 => 3 moves choose 1 down =3. So startToBlack=3. Subtract from j=0: ways((1,2)->(2,3)) = dx=1,dy=1 => C(2,1)=2. dp0=1, so subtract 12=2. So dp1=3-2=1.
Now bad: dp0ways((1,2)->(3,3)) = 1 * ways(1,2,3,3) = dx=2,dy=1? Actually (1,2) to (3,3): down 2, right 1 => C(3,2)=3? Wait total moves = 2+1=3, choose 2 down = C(3,2)=3. So contributes 3.
dp1*ways((2,3)->(3,3)) = 1 * ways(2,3,3,3) = dx=1,dy=0 => C(1,1)=1? Actually from (2,3) to (3,3): down 1 => C(1,1)=1. So contributes 1.
Total bad=4. ans=6-4=2. Correct.
Now scenario where there is a black cell that is not on any path from start to end? Could happen if it's beyond the grid? No all cells within grid. Actually all cells are within grid, and start and end are at (1,1) and (h,w). Any cell (r,c) with 1<=r<=h,1<=c<=w is on some path from start to end? Not necessarily: For a cell to be on some path from (1,1) to (h,w), it must satisfy that there exists a monotonic path that goes through it. Since we can always go from start to the cell (if r>=1,c>=1) and from cell to end (if r<=h,c<=w), all cells are on some path. Because from start to cell: need to go right and down enough; always possible as long as the cell is not left/up of start. Since start is top-left, any cell is reachable from start (you can go right and down). Also from cell to end: you need to go right and down to reach (h,w), which is possible because h>=r, w>=c. So all cells are on some path. So all black cells are relevant.
Now confirm DP correctness with large n.
Now potential improvement: Use coordinate compression? Not needed.
Now modular arithmetic: We'll use % MOD.
Now note: In dp[i] calculation, val can be negative after subtraction; we do val % MOD after subtraction, but careful: Python's % with negative yields positive remainder, but we might want to keep it modulo. So we can do val = (start_to_black[i] - sum_j) % MOD. That works because subtraction yields negative but % MOD yields correct mod.
Alternatively, we can compute sum_j mod, then dp[i] = (start_to_black[i] - sum_j) % MOD.
Now we must be careful about integer overflow? Python big ints fine.
Now confirm factorial precomputation limit. We set limit = h + w. But what about binomial arguments up to h+w-2? So limit = h+w is safe. But we might need factorial up to h+w? Actually the maximum n in comb could be (h+w-2). So we need fact up to h+w-2. So limit = h+w is enough. But we also need invfact up to that. So we can set N = h + w + 5.
Now check if h=100000, w=100000, then h+w=200000, so factorial array size 200001. That's fine.
Now double-check that we don't need to compute comb for arguments bigger than that. For ways from (1,1) to (h,w) we need comb(h+w-2, ...), so at most 200000-2=199998, so within 200k. So all good.
Now we should ensure that for each pair, we compute comb only if arguments non-negative.
Now we need to be careful about reading input: maybe there are extra spaces, but Python's split handles.
Now code.
But wait: The problem states "h × w field" and "upper left corner" to "lower right corner". Usually rows are numbered from top to bottom, columns from left to right. So moving down increases row, right increases column. So our interpretation matches.
Now possible pitfalls: Could there be a black cell that is before start? No.
Now final answer.
But wait, there is an alternative formula: the answer could be computed using principle of inclusion-exclusion over subsets of black cells but that would be 2^n impossible. So DP is correct.
Now we need to produce final answer.
Now I will write final code accordingly.
But also I realize that we can optimize by precomputing ways between all pairs, but not needed.
Now test with provided example 2 using a quick mental or approximate? Let's try to compute with code in head? Not needed, but trust.
Now also note that for large numbers, Python pow with exponent MOD-2 is fine.
Now final code.
But let's think about a subtle case: if a black cell is directly on the path from another black cell, and the two are in the same row or column, our DP works.
Now confirm that we treat start and end as white, so we don't need to include them as black.
Now consider scenario where some black cells are unreachable from start because they are located such that one must pass through another black cell? Actually reachable from start means there exists a path from start to that cell that does not pass through any black cell? No, reachable ignoring black cells is always possible. But our DP for start_to_black uses total ways ignoring black cells (i.e., all paths from start to that cell). That's correct because we later subtract paths that go through earlier black cells.
But if a black cell is such that all paths from start to it pass through some other black cell, then after subtraction, dp[i] would become zero. That's expected because any path that reaches that cell must have encountered a black cell earlier.
Now all good.
Now we need to ensure that we sort black cells correctly: key = (r,c). That's default tuple sorting.
Now we need to precompute factorial up to maxN. But note that h and w can be as high as 1e5, but n is up to 2000. So maxN up to 200000.
Now we can implement precomputation.
Potential performance: O(n^2) loops with inner loop may be okay. But we can micro-opt: we can precompute ways between all pairs maybe using DP of O(n^2) anyway. So we can compute on the fly.
Now one more nuance: In dp[i], we subtract dp[j] * ways(Pj->Pi) for all j where r_j <= r_i and c_j <= c_i. Since n is 2000, checking all j < i is okay, we don't need to filter with condition? We can filter quickly but it's okay to check all j < i and test condition; it's at most 2e6 checks, which is fine.
Now we need to be careful about Python recursion? No recursion.
Now finalize.
But before finalizing, let's check if we need to consider that the board size might be up to 1e5 and we need to compute factorials up to 200000, but 200000! mod 1e9+7 can be computed.
Now let's test with sample input in code.
Now final answer.
But wait, we have to ensure that we treat coordinates correctly: rows and columns both start at 1. That's fine.
Now consider extreme: h=1, w=100000, n=0. Then only one row, you can only move right. Total paths = C(0+99999,0?) Actually from (1,1) to (1,100000): need to move right (w-1) steps = 99999 steps, but you have no down moves. Number of ways = 1 (since only right moves). Our total: ways(1,1,1,100000): dx=0, dy=99999 => comb(99999,0)=1. Good.
If there is a black cell somewhere, then dp will compute accordingly. For h=1, all cells are in a single row. Only paths go through all intermediate columns. If any black cell is on the path, then no path can avoid it because you must pass through each column. Actually you could skip a column? You must move right through each column sequentially. So if there is a black cell anywhere between 1 and w, then the only path from start to end must go through that cell. So answer = 0 unless the black cell is at start or end (but those are white). So answer=0. Let's test: h=1,w=5, black at (1,3). total paths = 1. dp[0] = ways(1,1,1,3)=1 (only path). dp[0]=1. bad = dp0 * ways((1,3)->(1,5)) =1 * ways(1,3,1,5) = comb(2,0)=1. So total - bad =0. Good.
Now h=1, w=5, black at (1,2) and (1,4). Both black. total=1. Sorted: (1,2),(1,4). dp0 = ways(1,1,1,2)=1. dp1 = ways(1,1,1,4)=1 - dp0ways((1,2)->(1,4))=1 - 11 =0. Then bad = dp0ways(1,2->1,5)=11=1 + dp1ways(1,4->1,5)=01=0 => bad=1, ans=0. Good.
Now consider a case where there is a black cell that is not on the only path but still reachable? For h=1, any cell is on the only path; so ok.
Now consider w=1 similarly.
Now check scenario with large numbers.
Now code.
But note: There is a possible alternative approach using combinatorics with barriers (like counting lattice paths avoiding obstacles) that is essentially the same.
Now I'll produce final answer.
But there is a nuance: The board is "Giant chess" but moves only down/right, not like knight etc.
Now I think it's correct.
Now let's write final Python code.
Potential improvement: Use sys.stdin.read() to read all input quickly. But not needed.
We'll produce:
import sys
MOD = 10**9+7
def precompute_fact(limit):
fact = [1]*(limit+1)
for i in range(1, limit+1):
fact[i] = fact[i-1]i % MOD
inv_fact = [1](limit+1)
inv_fact[limit] = pow(fact[limit], MOD-2, MOD)
for i in range(limit, 0, -1):
inv_fact[i-1] = inv_fact[i]*i % MOD
return fact, inv_fact
def comb(n, k, fact, inv_fact):
if k < 0 or k > n:
return 0
return fact[n] * inv_fact[k] % MOD * inv_fact[n-k] % MOD
def main():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
h = int(next(it))
w = int(next(it))
n = int(next(it))
black = []
for _ in range(n):
r = int(next(it)); c = int(next(it))
black.append((r,c))
black.sort()
maxN = h + w # enough for all binomials
fact, inv_fact = precompute_fact(maxN)
def ways(r1,c1,r2,c2):
if r1 > r2 or c1 > c2:
return 0
dx = r2 - r1
dy = c2 - c1
return comb(dx+dy, dx, fact, inv_fact)
total = ways(1,1,h,w)
start_to_black = [ways(1,1,r,c) for (r,c) in black]
m = len(black)
dp = [0]*m
for i in range(m):
r_i, c_i = black[i]
val = start_to_black[i]
for j in range(i):
r_j, c_j = black[j]
if r_j <= r_i and c_j <= c_i:
val -= dp[j] * ways(r_j, c_j, r_i, c_i)
dp[i] = val % MOD
bad = 0
for i in range(m):
r_i, c_i = black[i]
bad = (bad + dp[i] * ways(r_i, c_i, h, w)) % MOD
ans = (total - bad) % MOD
print(ans)
if name == "main":
main()
Now test with examples.
Example1:
Input:
3 4 2
2 2
2 3
Our code yields 2.
Example2: let's simulate quickly with Python? Hard but trust.
Now potential off-by-one: maxN = h + w may not be enough if we need factorial up to h + w? Actually we need up to (h+w-2). So h+w is more than enough. But what about comb(dx+dy, dx) where dx+dy could be up to (h-1)+(w-1)=h+w-2. So if we compute factorial up to h+w, that includes h+w which is larger than needed, but that's fine. But we must ensure that we precompute up to at least h+w-2. So using h+w is safe.
But wait, what if we compute ways from (1,1) to (h,w) we need n = (h-1)+(w-1) = h+w-2. So we need factorial up to h+w-2. But we set maxN = h+w, which is >= h+w-2, okay. However, in precompute_fact, we need to allocate up to maxN, which could be 200000. That's fine.
But there is a subtle case: if h=100000, w=100000, h+w=200000, our factorial array size 200001. That's okay.
Now there is also possibility that we might need factorial for numbers up to 200000. The modulo operations fine.
Now one more check: In dp calculation, we do val -= dp[j] * ways(...). Since dp[j] is modulo MOD, ways also modulo MOD, product might be large but Python handles. After subtracting many, we mod at end. Fine.
Now let's test on some random small cases by brute force to ensure correctness.
We can write a small test offline, but not possible here. But we can reason.
Now final answer: we produce the code.
But before concluding, I recall a known problem: CF 559C? Actually this is Codeforces problem "Gerald and Giant Chess" (CF 559C). Yes, exactly. The solution is DP with sorting and binomial coefficients. So it's correct.
def main() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
h = int(next(it))
w = int(next(it))
n = int(next(it))
code
black = []
for _ in range(n):
r = int(next(it))
c = int(next(it))
black.append((r, c))
black.sort() # by row, then column
max_sum = h + w # enough for all binomial arguments
fact, inv_fact = precompute_fact(max_sum)
def ways(r1, c1, r2, c2) -> int:
"""Number of monotone paths from (r1,c1) to (r2,c2)."""
if r1 > r2 or c1 > c2:
return 0
dr = r2 - r1
dc = c2 - c1
return comb(dr + dc, dr, fact, inv_fact)
total = ways(1, 1, h, w)
start_to = [ways(1, 1, r, c) for (r, c) in black]
m = len(black)
dp = [0] * m
for i in range(m):
ri, ci = black[i]
val = start_to[i]
for j in range(i):
rj, cj = black[j]
if rj <= ri and cj <= ci:
val -= dp[j] * ways(rj, cj, ri, ci)
dp[i] = val % MOD
bad = 0
for i in range(m):
ri, ci = black[i]
bad = (bad + dp[i] * ways(ri, ci, h, w)) % MOD
answer = (total - bad) % MOD
print(answer)