基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
收藏
关注
M * N的方格,一个机器人从左上走到右下,只能向右或向下走。有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10^9 + 7的结果。
Input
第1行,2个数M,N,中间用空格隔开。(2 <= m,n <= 1000000)
Output
输出走法的数量 Mod 10^9 + 7。
Input示例
2 3
Output示例
3
从左上角到右下角,从(1,1)到(m,n),水平需要走n-1步
步,竖直需要走m-1步,水平竖直的顺序随机组合就可以
所以是C(n-1+m-1,min(n-1,m-1))种方法
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int p = 1e9+7;
ll quick_mod(ll a,ll b){//快速幂求逆元
ll ans = 1;
a %= p;
while(b){
if(b&1){
ans = ans*a%p;
b--;
}
b >>= 1;
a = a*a%p;
}
return ans;
}
/*ll quick_mod(ll a ,ll b){//这个也是快速幂求逆元的
if(b==0) return 1;
ll res = quick_mod(a*a%p,b/2);
if(b%2)
res = res*a%p;
return res;
}*/
ll C(ll n,ll m){//求组合数C(n,m)
if(m>n) return 0;
ll ans = 1;
for(ll i=1;i<=m;i++){
ll a=(n-m+i)%p;
ll b = i%p;
ans = ans*(a*quick_mod(b,p-2)%p)%p;
}
return ans;
}
ll Lucas(ll n,ll m){//卢卡斯定理
return m==0?1:(C(n%p,m%p)*Lucas(n/p,m/p)%p);
}
int main()
{
int n,c;
while(cin >> n >> c){
cout << Lucas(n+c-2,min(n,c)-1)<<endl;
}
return 0;
}