Harvest of Apples(逆元+莫队+组合数学)

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 1e9+7.

Sample Input
2
5 2
1000 500

Sample Output
16
924129523

求C(n,0)+C(n,1)+C(n,2)+…+C(n,m);

设S(n,m)=C(n,0)+C(n,1)+C(n,2)+…+C(n,m);

S(n, m) = 2 * S(n - 1, m) - C(n - 1, m)

#include<iostream>
#include<stdio.h>
#include<cmath>
#include<algorithm>
using namespace std;
const int mod=1e9+7;
#define ll long long
const int maxn=1e5+7;
ll jiecheng[maxn],inv[maxn];
ll ans[maxn];
int block;
ll qsm(ll a,ll b)
{
    ll ans=1;
    while(b){
        if(b&1)
            ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
void init()
{
    jiecheng[1] = 1;
    for(int i = 2; i < maxn; i++)
        jiecheng[i] = jiecheng[i-1] * i % mod;
    for(int i = 1; i < maxn; i++)
        inv[i] = qsm(jiecheng[i], mod-2);
}
struct node{
    int l,r;
    int i;
}modui[maxn];
bool cmp(node a,node b)
{
    if(a.l/block==b.l/block)
        return a.r<b.r;
    return a.l<b.l;
}
ll C(ll n,ll m)
{
    
    if(m == 0 || m == n) return 1;
    ll ans=1;
    ans=(jiecheng[n]*inv[m])%mod*inv[n-m];
    ans=ans%mod;
    return ans;
}
int main()
{
    init();
    block = sqrt(maxn);
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++)
    {
        scanf("%d%d",&modui[i].l,&modui[i].r);
        modui[i].i=i;
    }
    sort(modui,modui+t,cmp);
    int l=1,r=0;
    int sum=1;
    for(int i = 0; i < t; i++)
    {
        while(l < modui[i].l) sum = (2 * sum - C(l++, r) + mod) % mod;
        while(l > modui[i].l) sum = ((sum + C(--l, r))*inv[2]) % mod;
        while(r < modui[i].r) sum = (sum + C(l, ++r)) % mod;
        while(r > modui[i].r) sum = (sum - C(l, r--) + mod) % mod;
        ans[modui[i].i] = sum;
    }
    for(int i=0;i<t;i++)
    {
        printf("%lld\n",ans[i]);
    }
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值