Problem B. Harvest of Apples
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 3573 Accepted Submission(s): 1380
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
Source
2018 Multi-University Training Contest 4
Recommend
chendu
题意:
求的和
思路:
因为可以O(1)的从S(n,m)转移到S(n,m+1),S(n,m-1),S(n+1,m),S(n-1,m)。所以可以考虑莫队。
由S(n,m)到S(n,m+1)有,S(n,m+1)=S(n,m)+C(n,m+1)
而由S(n,m)到S(n+1,m),根据
S(n+1,m)=2*S(n,m)-C(n,m)
所以我们就可以用莫队算法来求解了。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=1e5+5;
const int mod=1e9+7;
typedef long long ll;
ll ans=1;
ll res[maxn];
ll fac[maxn]={1,1},inv[maxn]={1,1},f[maxn]={1,1};
struct node
{
int l,r;
int id;
}q[maxn];
int pos[maxn];
bool cmp(node a,node b)
{
if(pos[a.l]==pos[b.l])
return a.r<b.r;
return pos[a.l]<pos[b.l];
}
ll cal(ll a,ll b)
{
if(b>a)
return 0;
return fac[a]*inv[b]%mod*inv[a-b]%mod;
}
void init()
{
for(int i=2;i<maxn;i++){
fac[i]=fac[i-1]*i%mod;
f[i]=(mod-mod/i)*f[mod%i]%mod;
inv[i]=inv[i-1]*f[i]%mod;
}
}
int main()
{
int t;
scanf("%d",&t);
int sz=sqrt(maxn);
init();
for(int i=0;i<maxn;i++){
pos[i]=i/sz;
}
for(int i=1;i<=t;i++){
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+1+t,cmp);
int L=1,R=0;
for(int i=1;i<=t;i++){
while(L<q[i].l) ans=(2ll*ans%mod-cal(L++,R)+mod)%mod;
while(L>q[i].l) ans=(ans+cal(--L,R))%mod*f[2]%mod;
while(R<q[i].r) ans=(ans+cal(L,++R))%mod;
while(R>q[i].r) ans=(ans-cal(L,R--)+mod)%mod;
res[q[i].id]=ans;
}
for(int i=1;i<=t;i++){
printf("%lld\n",res[i]);
}
return 0;
}