1. 程式人生 > >51nod1119 機器人走方格 組合數學

51nod1119 機器人走方格 組合數學

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 1000000007

LL 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;
}