2018 Multi-University Training Contest 4 B(Harvest of Apples)
Problem Description
There are n apples on a tree, numbered from 1 to n.
Count the number of ways to pick at most m apples.
Input
The first line of the input contains an integer T (1≤T≤105) denoting the number of test cases.
Each test case consists of one line with two integers n,m (1≤m≤n≤105).
Output
For each test case, print an integer representing the number of ways modulo 109+7.
Sample Input
2
5 2
1000 500
Sample Output
16
924129523
题意:给出n和m,求C(n,0)+C(n,1)+...C(n,m)。
官方题解:
这道题几乎就是到莫队模版题。
莫队算法就是最基本的就可以,离线左右测试样例,然后可以把S(n,m)看成一个二维的,只要保证可以向四个方向跳,就可以在nsqrt(n)之内算出所有ans。
const int maxn =1e5+5;
const int mod = 1e9+7;
LL fac[maxn],inv[maxn];
LL rev2;
LL qpow(LL b,int n)
{
LL res=1;
while(n)
{
if(n&1) res=res*b%mod;
b = b*b%mod;
n>>=1;
}
return res;
}
LL Comb(int n,int k)
{
return fac[n]*inv[k]%mod *inv[n-k]%mod;
}
void pre()
{
rev2=qpow(2,mod-2);
fac[0]=fac[1]=1;
for(int i=2;i<maxn;++i) fac[i]=i*fac[i-1]%mod;
inv[maxn-1]=qpow(fac[maxn-1],mod-2);
for(int i=maxn-2;i>=0;i--) inv[i]=inv[i+1]*(i+1)%mod;
}
int pos[maxn];
struct Query
{
int L,R,id;
bool operator <(const Query& p) const
{
if(pos[L]==pos[p.L]) return R<p.R;
return L<p.L;
}
}Q[maxn];
LL res;
LL ans[maxn];
inline void addN(int posL,int posR)
{
res = (2*res%mod - Comb(posL-1,posR)+mod)%mod;
}
inline void addM(int posL,int posR)
{
res = (res+Comb(posL,posR))%mod;
}
inline void delN(int posL,int posR)
{
res = (res+Comb(posL-1,posR))%mod *rev2 %mod;
}
inline void delM(int posL,int posR)
{
res = (res-Comb(posL,posR)+mod)%mod;
}
int main()
{
int T,N,M,u,v,tmp,K;
int a,b;
pre();
int block = (int)sqrt(1.0*maxn);
for(int i=0;i<maxn;i++) pos[i]=i/block;
scanf("%d",&T);
for(int i=1;i<=T;++i)
{
scanf("%d%d",&Q[i].L,&Q[i].R);
Q[i].id = i;
}
sort(Q+1,Q+T+1);
res=2;
int curL=1,curR=1;
for(int i=1;i<=T;++i)
{
while(curL<Q[i].L) addN(++curL,curR);
while(curR<Q[i].R) addM(curL,++curR);
while(curL>Q[i].L) delN(curL--,curR);
while(curR>Q[i].R) delM(curL,curR--);
ans[Q[i].id]=res;
}
for(int i=1;i<=T;++i) printf("%lld\n",ans[i]);
return 0;
}