题解:首先,M*N个方格,机器人每步只能向下或向右走,一共要走m+n-2步,而其中必须有m-1步向下,n-1步向右。也就是一个C什么什么的组合问题。
其次,题目数据要求取模,然而组合数中有除法,除法不可以直接取模,需要将除法转化为乘法,也就是乘以除法逆元。
求逆元常用的方法有费马小定理和扩展欧几里得法。费马小定理直接求a^(p-2)即可(p是mod的值)。而扩展欧几里得法就是将a,p代入方程,求出的x就是逆元。
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 50005;
const int mod = 1e9 + 7;
LL exgcd(LL a, LL b, LL &x, LL &y)
{
if(a == 0 && b == 0)
{
return -1;
}
if(b == 0)
{
x = 1;
y = 0;
return 0;
}
LL d = exgcd(b, a%b, y, x);
y -= a / b * x;
return d;
}
//逆元
LL mod_reverse(LL a, LL n)
{
LL x, y;
LL d = exgcd(a, n, x, y);
//if(d == 1)
//return (x % n + n) % n;
//else
//return -1;
return (x % n + n) % n;
}
LL C(LL m, LL n)
{
LL i, t1, t2;
t1 = t2 = 1;
for(i = n; i >= n-m+1; --i)
{
t1 = t1 * i % mod;
}
for(i=1; i <= m; ++i)
{
t2 = t2 * i % mod;
}
return t1 * mod_reverse(t2, mod) % mod;
}
int main() {
LL m, n;
cin >> m >> n;
cout << C( min(m-1, n-1), m+n-2);
return 0;
}