瞬间移动
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1228 Accepted Submission(s): 607
Problem Description
有一个无限大的矩形,初始时你在左上角(即第一行第一列),每次你都可以选择一个右下方格子,并瞬移过去(如从下图中的红色格子能直接瞬移到蓝色格子),求到第
n行第
m列的格子有几种方案,答案对
1000000007取模。

Input
多组测试数据。
两个整数 n,m(2\leq n,m\leq 100000)
两个整数 n,m(2\leq n,m\leq 100000)
Output
一个整数表示答案
Sample Input
4 5
Sample Output
10
Source
Recommend
wange2014
此题为公式题,难度在于推公式,公式推出来就套模板。
分析:一个无限大的矩形,要求从(1,1)到(m,n),只可以走斜下方的方块,将图斜过来看,可以看作是一个
杨辉三角的形状,例如需要到达(4,6)的位置,如图所示,其中首先灰色方块不能选,因为只能走斜向右下的方块
,在空白部分,将图旋转45°,建立一个杨辉三角数阵,发现所求的(4,6)方块在建立的数阵的第7层,通过实验多
组数据,发现方块坐标所处的层数是(m+n-3),则需要从前(m+n-4)层中选择(n-2)或(m-2)个格子,因为得
去掉(n-1)行和(m-1)列(不能选纯1列),还有得去掉第一行和第一列,因此每一层只能选(m-2)或(n-2)个
格子,因此最后的公式为
C(m+n−4,n −2)=(n+m−4)!(n−2)!∗(m−2)!
C(m+n−4,n −2)=(n+m−4)!(n−2)!∗(m−2)!
代码需要用到卢卡斯定理,具体实现的参考代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <set>
#include <map>
#include <cstdlib>
#include <functional>
#include <climits>
#include <cctype>
#include <iomanip>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define clr(a, x) memset(a, x, sizeof(a))
const int mod = 1e9 + 7;
const double eps = 1e-6;
ll quick_mod(ll a, ll b)
{
ll ans = 1;
a %= mod;
while (b)
{
if (b & 1)
{
ans = ans * a % mod;
b--;
}
b >>= 1;
a = a * a % mod;
}
return ans;
}
ll comb(ll n, ll m)
{
if (m > n)
return 0;
ll ans = 1;
for (int i = 1; i <= m; i++)
{
ll a = (n + i - m) % mod;
ll b = i % mod;
ans = ans * (a * quick_mod(b, mod - 2) % mod) % mod;
}
return ans;
}
ll Lucas(ll n, ll m)
{
if (m == 0)
return 1;
return comb(n % mod, m % mod) * Lucas(n / mod, m / mod) % mod;
}
int main()
{
int m, n;
scanf("%d%d", &m, &n);
printf("%lld\n", Lucas(m + n - 4, n - 2));
return 0;
}