Qwerty78 is a well known programmer (He is a member of the ICPC WF winning team in 2015, a topcoder target and one of codeforces top 10).
He wants to go to Dreamoon's house to apologize to him, after he ruined his plans in winning a Div2 contest (He participated using the handle"sorry_Dreamoon") so he came first and Dreamoon came second.
Their houses are presented on a grid of N rows and M columns. Qwerty78 house is at the cell (1, 1) and Dreamoon's house is at the cell (N, M).
If Qwerty78 is standing on a cell (r, c) he can go to the cell (r + 1, c) or to the cell (r, c + 1). Unfortunately Dreamoon expected Qwerty78 visit , so he put exactly 1 obstacle in this grid (neither in his house nor in Qwerty78's house) to challenge Qwerty78. Qwerty78 can't enter a cell which contains an obstacle.
Dreamoon sent Qwerty78 a message "In how many ways can you reach my house?". Your task is to help Qwerty78 and count the number of ways he can reach Dreamoon's house. Since the answer is too large , you are asked to calculate it modulo 109 + 7 .
The first line containts a single integer T , the number of testcases.
Then T testcases are given as follows :
The first line of each testcase contains two space-separated N , M ( 2 ≤ N, M ≤ 105)
The second line of each testcase contains 2 space-separated integers OR, OC - the coordinates of the blocked cell (1 ≤ OR ≤ N) (1 ≤ OC ≤ M).
Output T lines , The answer for each testcase which is the number of ways Qwerty78 can reach Dreamoon's house modulo 109 + 7.
1 2 3 1 2
1
Sample testcase Explanation :
The grid has the following form:
Q*.
..D
Only one valid path:
(1,1) to (2,1) to (2,2) to (2,3).
题解:
组合数,一个矩形只能往右或者下走,中间一个格子有石头,问有多少中走法;
C(n + m - 2, n - 1) - C(n+m-r-c, n-r)*C(r+c-2, r-1)
总的减去经过格子的方法就是所要结果,但是存在取模,所以要用到逆元;
代码:
#include#include #include #include #include using namespace std;const int MOD = 1e9 + 7;const int MAXN = 2e5 + 100;typedef __int64 LL;LL fac[MAXN];void init(){ fac[0] = 1; for(int i = 1; i < MAXN; i++){ fac[i] = fac[i - 1] * i % MOD; }}LL quick_mul(LL a, LL n){ LL ans = 1; while(n){ if(n & 1){ ans = ans * a % MOD; } n >>= 1; a = a * a % MOD; } return ans;}LL C(int n, int m){ return fac[n] * quick_mul(fac[m], MOD - 2) % MOD * quick_mul(fac[n - m], MOD - 2) % MOD;}int main(){ int T, n, m, r, c; scanf("%d", &T); init(); while(T--){ scanf("%d%d%d%d", &n, &m, &r, &c); printf("%I64d\n", (C(n + m - 2, n - 1) - C(n+m-r-c, n-r)*C(r+c-2, r-1)%MOD + MOD) % MOD); } return 0;}