有一个无限大的矩形,初始时你在左上角(即第一行第一列),每次你都可以选择一个右下方格子,并瞬移过去(如从下图中的红色格子能直接瞬移到蓝色格子),求到第n行第m列的格子有几种方案,答案对1000000007取模。
Input
多组测试数据。
两个整数n,m(2≤n,m≤100000)
Output
一个整数表示答案
Sample Input
4 5
Sample Output
10
分析: 题意很容易搞懂,重点是怎么把规律找出来
首先自己写4组数据
n m ans
5 2 1
5 3 4
5 4 10
5 5 20
然后杨辉三角打表
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
我们发现规律就是求组合数C(n+m-4,m-2)
然后数据范围1e5,O(n^2)肯定过不了,所以O(n)算法求组合数
注意: 1e5交上去会RE,最好数组开大一点
AC代码:
#include<iostream>
#include<cstdio>
using namespace std;
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define rev(i,s,e) for(int i=e;i>=s;i--)
#define all(x) x.begin(),x.end()
#define sz(x) x.size()
#define szz(x) int(x.size()-1)
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int MAXN = 2e5+10;
typedef long long LL;
typedef pair<LL,LL> PII;
LL fat[MAXN];
void exgcd(LL a,LL b,LL &x,LL &y,LL &d)
{
if(!b) d=a,x=1,y=0;
else exgcd(b,a%b,y,x,d),y-=(a/b)*x;
}
LL inv(LL a,LL p)
{
LL x,y,d;
exgcd(a,p,x,y,d);
return d==1?(x%p+p)%p:-1;
}
void cal()
{
fat[0] = fat[1] = 1;
for(LL i = 2;i<MAXN;i++)
fat[i] = (fat[i-1]*i)%MOD;
}
LL c(LL n,LL m)
{
return fat[n]*inv(fat[m],MOD)%MOD*inv(fat[n-m],MOD)%MOD;
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif // LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
LL n,m;
cal();
while(cin>>n>>m)
{
cout<<c(n+m-4,m-2)<<endl;
}
return 0;
}
无限矩形瞬移路径计数

探讨在无限大的矩形中,从左上角通过特定规则瞬移至指定位置的不同路径数量计算方法。利用杨辉三角表找到组合数规律,并采用高效算法实现大范围数据的快速计算。
13万+





