第1行,2个数M,N,中间用空格隔开。(2 <= m,n <= 1000000)
输出走法的数量 Mod 10^9 + 7。
2 3
3
思路:就是一个数学组合问题。。。( C(n-1+m-1,n-1) )一直不知道除法取模怎么算,今天学习了一下,用到了费马小定理。
带模的除法:求 a / b = x (mod M) 只要 M 是一个素数,而且 b 不是 M 的倍数,就可以用一个逆元整数 b’,通过 a / b = a * b' (mod M),来以乘换除。 费马小定理说,对于素数 M 任意不是 M 的倍数的 b,都有:b ^ (M-1) = 1 (mod M) 于是可以拆成:b * b ^ (M-2) = 1 (mod M) 于是:a / b = a / b * (b * b ^ (M-2)) = a * (b ^ (M-2)) (mod M) 也就是说我们要求的逆元就是 b ^ (M-2) (mod M)! ——(用快速幂可以求出)
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <set> #include <queue> using namespace std; const int mod = 1000000007; const int MAXN = 1000000; long long f[MAXN * 2 + 10]; int n,m; void init() { f[0] = 1; f[1] = 1; for(int i = 2; i <= 2000000; i++) f[i] = (f[i - 1] * i) % mod; } long long pow(long long n,long long m) { long long ans = 1; while(m > 0) { if(m & 1)ans = (ans * n) % mod; m = m >> 1; n = (n * n) % mod; } return ans; } long long computer() { long long ans = f[n - 1 + m - 1]; ans = (ans * pow(f[n-1],mod - 2)) % mod; ans = (ans * pow(f[m - 1] ,mod - 2)) % mod; return ans; } int main() { // freopen("in.txt","r",stdin); init(); while(~scanf("%d%d",&n,&m)) { cout<<computer()<<endl; } return 0; }