51nod1119 机器人走方格 组合数学

来源:互联网 发布:u盘数据恢复后打不开 编辑:程序博客网 时间:2024/05/18 03:32

M * N的方格,一个机器人从左上走到右下,只能向右或向下走。有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10^9 + 7的结果。


题目本身很简单,就是一个初中都推倒过的理论,只能向下或者向右的话,那么可能的路径一共有C(n+m,n)种。很好理解的这里就不说明了。现在我们要解决的是,当n和m都比较大的时候怎么讲结果计算出来。





#include <cmath>#include <iostream>#include <cstring>#include "minmax.h"#include <cstdio>using namespace std ;#define LL long long#define p 1000000007LL n, m;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 C(LL n, LL m){if (m > n) return 0;LL ans = 1;for (int i = 1; i <= m; i++){LL a = (n + i - m) % p;LL b = i % p;ans = ans * (a * quick_mod(b, p - 2) % p) % p;}return ans;}LL Lucas(LL n, LL m){if (m == 0) return 1;return C(n % p, m % p) * Lucas(n / p, m / p) % p;}int main(){while (cin>>n>>m){LL a = n + m - 2;LL b = min(n, m) - 1;printf("%I64d\n", Lucas(a,b));}return 0;}




0 0
原创粉丝点击