Harvest of Apples
Time Limit: 4000/2000 MS (Java/Others)
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
题意:1e5次询问,每次一个n和m,问C(n,0)+C(n,1)+...+C(n,m)的值.
思路:做来做去发现没有什么公式可言,值得出来一个简单递推式,S(n,m) = S(n,m-1)+C(n,m),S(n,m) = 2S(n-1,m)-C(n-1,m)
所以如果我们知道S(n,m),就可以立马推出S(n-1,m),S(n,m-1),S(n+1,m),S(n,m+1),关于C(n,m)的计算我们可以提前打好表.
所以我们可以用莫队算法搞一搞.
代码:
#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
const ll mod = 1e9+7;
const double eps = 1e-12;
const int inf = 0x3f3f3f3f;
map<int,int>::iterator it;
struct node
{
int l,r;
int pos,stock;
}a[maxn];
int n,len;
ll inv[maxn],fac[maxn],ans[maxn];
ll quick_pow(ll x,ll y)
{
ll ans = 1;
while(y)
{
if(y&1)
ans = ans*x%mod;
y>>= 1;
x = x*x%mod;
}
return ans;
}
void init()//打表
{
inv[0] = fac[0] = 1;
for(int i = 1;i<= 100000;i++)
{
fac[i] = fac[i-1]*i%mod;
inv[i] = quick_pow(fac[i],mod-2);
}
}
bool cmp(node x,node y)
{
if(x.stock == y.stock) return x.r< y.r;
return x.stock< y.stock;
}
ll C(int x,int y)
{
return (fac[x]*inv[y]%mod*inv[x-y]%mod);
}
int main()
{
init();
cin>>n;
len = sqrt(n);
for(int i = 1;i<= n;i++)
{
scanf("%d %d",&a[i].r,&a[i].l);
a[i].pos = i;
a[i].stock = a[i].l/len;
}
sort(a+1,a+n+1,cmp);
int l = 1,r = 1;
ll sum = 2;
for(int i = 1;i<= n;i++)
{
while(r< a[i].r) sum = (sum+sum+mod-C(r,l))%mod,r++;
while(l> a[i].l) sum = (sum+mod-C(r,l))%mod,l--;
while(r> a[i].r) sum = (sum+C(r-1,l))*inv[2]%mod,r--;
while(l< a[i].l) sum = (sum+C(r,l+1))%mod,l++;
ans[a[i].pos] = sum;
}
for(int i = 1;i<= n;i++)
printf("%lld\n",ans[i]);
return 0;
}