[组合数学]Many Many Paths
题意
给定\(r1,c1,r2,c2\),求\(\sum^{r2}_{i=r1}{\sum^{c2}_{j=c1}{f(i,j)}}\),其中\(f(i,j)\)表示从\((0,0)\)往上或往右走到\((i,j)\)的方案数
题解
设\(g(r,c)=\sum^{r}_{i=0}{\sum^{c}_{j=0}{f(i,j)}}\)
则\(\sum^{r2}_{i=r1}{\sum^{c2}_{j=c1}{f(i,j)}}=g(r2,c2)-g(r1-1,c2)-g(r2,c1-1)+g(r1-1,c1-1)\)
又\(f(i,j)={i+j \choose j}\)(显然)
则\(g(r,c)=\sum^{r}_{i=0}{\sum^{c}_{j=0}{f(i,j)}}=\sum^{r}_{i=0}{\sum^{c}_{j=0}{{i+j \choose j}}}\)
又\(\sum^{c}_{j=0}{{i+j \choose j}}={i+c+1 \choose c}\)(这是一个公式)
则\(g(r,c)=\sum^{r}_{i=0}{\sum^{c}_{j=0}{f(i,j)}}=\sum^{r}_{i=0}{\sum^{c}_{j=0}{{i+j \choose j}}}=\sum^{r}_{i=0}{{i+c+1 \choose c}}\)
因此\(g(r,c)\)可以在\(O(n)\)时间内求出
代码
#include<bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
ll f[2000010],invf[2000010];
ll qpow(ll a,ll b){
ll ret=1;
while(b){
if(b&1) ret=ret*a%mod;
a=a*a%mod;
b>>=1;
}
return ret;
}
void init(ll n=2000005){
f[0]=1;
for(ll i=1;i<=n;i++) f[i]=f[i-1]*i%mod;
invf[n]=qpow(f[n],mod-2);
for(ll i=n-1;i>=0;i--) invf[i]=invf[i+1]*(i+1)%mod;
}
ll C(ll n,ll m){//O(1)
if(m>n||m<0) return 0; if(m==n||m==0) return 1;
return f[n]*invf[m]%mod*invf[n-m]%mod;
}
ll g(ll r,ll c){
ll ret=0;
for(ll i=0;i<=r;i++){
ret=(ret+C(i+c+1,c))%mod;
}
return ret;
}
int main()
{
init();
ll r1,c1,r2,c2;scanf("%lld%lld%lld%lld",&r1,&c1,&r2,&c2);
ll ans=(((g(r2,c2)-g(r1-1,c2))%mod-g(r2,c1-1))%mod+g(r1-1,c1-1))%mod;
ans=(ans+mod)%mod;
printf("%lld\n",ans);
return 0;
}
转载请注明出处:https://www.cnblogs.com/lllxq/