杭电多校 Problem B. Harvest of Apples

问题 B: Problem B. Harvest of Apples

时间限制: 5 Sec  内存限制: 256 MB
提交: 3  解决: 3
[提交] [状态] [讨论版] [命题人:admin]

题目描述

/upload/file/20180801/20180801122228_53314.pdf 
There are n apples on a tree, numbered from 1 to n.
Count the number of ways to pick at most m apples. 

输入

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).

输出

For each test case, print an integer representing the number of ways modulo 109+7.

样例输入

扫描二维码关注公众号,回复: 2594776 查看本文章
2
5 2
1000 500

样例输出

16
924129523

[提交][状态]

题解:可以进行分块离线莫队,比赛的时候倒是忘记了T也可以离线了,定义S(n,m)=从C(n,0)+到C(n,m)的和,不难发现S(n,m)可以推出S(n+1,m),S(n-1,m),S(n,m+1),S(n,m-1)可以采用莫队算法。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
const int inf=1e9;
const int maxn=1e5+5;
const int mod=1e9+7;
typedef long long ll;

ll res,rev2;
struct node
{
    int l,r,id;
}p[maxn];

ll qpow(ll a,int b)
{
    ll ans=1;
    a%=mod;
    while(b)
    {
        if(b&1)
            ans=(ans*a)%mod;
        a=(a*a)%mod;
        b/=2;
    }
    return ans;
}

ll inv[maxn],fac[maxn],ans[maxn],pos[maxn];
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 cmp(node a,node b)
{
    if(pos[a.l]!=pos[b.l])
        return a.l<b.l;
    return a.r<b.r;
}

ll Comb(int n,int k)
{
    return fac[n]*inv[k]%mod *inv[n-k]%mod;
}

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()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);

    pre();
    int t;
    scanf("%d",&t);

    int block=(int)sqrt(1.0*maxn);
    for(int i=1;i<=t;i++)
    {
        scanf("%d%d",&p[i].l,&p[i].r);
        pos[i]=i/block;
        p[i].id=i;
    }

    sort(p+1,p+1+t,cmp);

    res=2;
    int curL=1,curR=1;
    for(int i=1;i<=t;++i)
    {
        while(curL<p[i].l) addN(++curL,curR);
        while(curR<p[i].r) addM(curL,++curR);
        while(curL>p[i].l) delN(curL--,curR);
        while(curR>p[i].r) delM(curL,curR--);
        ans[p[i].id] = res;
    }
    for(int i=1;i<=t;i++)
        printf("%lld\n",ans[i]);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/sudu6666/article/details/81354905