2018 Multi-University Training Contest 4 Harvest of Apples (Hdu6333-分块莫队)

Problem B. Harvest of Apples

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1717    Accepted Submission(s): 659


 

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

题目大意:

输入测试样例t,接下来输入t行,输入n,m,输出 ,即组合数的和。

解题思路:

官方解释:

解释下这个:, 因为C(n,n-m)=C(n-1,m-1)+C(n-1,m),比如求S(5,2)=C(5,0)+C(5,1)+C(5,0)=0+C(4,0)+C(4,0)+C(4,1)+C(4,1)+C(4,2)=2*S(4,2)-C(4,2),规律差不多就是这样了,那我们只要打个阶乘表和逆元表我们就能以 O(1) 的代价计算出 S(n - 1, m), S(n, m - 1), S(n + 1, m), S(n, m + 1),接下来我们就可以用莫队加加减减了

代码:

#include

using namespace std;
#define LL long long
const LL MAXN =1e5+5;
const LL mod=1e9+7; //这里被坑的死死的,少了个const就TLE,我也不知道为啥,求大佬们解释 

LL fac[MAXN]; //阶乘表 
LL inverse[MAXN]; //逆序数表 
struct node{ //利用结构体储存组合数,方便进行分块 
    LL n,m,id,num;
}setd[MAXN];
LL sum;
LL quick_mod(LL a,LL b){ //快速幂求逆元 
    LL ans=1;
    a%=mod;
    while(b){
        if(b&1){
            ans=ans*a%mod;
        }
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
bool cmp(node a,node b){ //分块排序:如果块相同则按友区间从小到大排序,如果不同按块排序 
    return a.num==b.num?a.m=0;i--){ //求逆元表  
        inverse[i]=inverse[i+1]*(i+1)%mod; //因为fac[i]=fac[i+1]/(i+1),inverse[i]=fac[i]^(mod-2),inverse[i]=fac[i+1]^(mod-2)*(1/i+1)^(mod-2),因为*(1/(i+1))^(mod-2),即除以1/(i+1)所以inverse[i]=inverse[i+1]*(i+1)
    }
}
LL getC(LL n,LL m) //求组合数 
{
    if(m>n)
    return 0;
    return fac[n]*inverse[n-m]%mod*inverse[m]%mod;
}
int main()
{
    LL divide=sqrt(1e5);//分块 
    LL t;
    init();
    LL chu=quick_mod(2,mod-2);//将2求逆元 
    //printf("%lld\n",mod);
    while(~scanf("%lld",&t)){
        for(int i=1;i<=t;i++){
            scanf("%lld %lld",&setd[i].n,&setd[i].m);
            setd[i].id=i;
            setd[i].num=(setd[i].n)/divide;
        }
        sort(setd+1,setd+1+t,cmp); //排序	 
        LL l=0,r=0;
        LL ans[MAXN];
        sum=1;
        for(LL i=1;i<=t;i++){ //按照上述公式进行莫队算法, 
            while(lsetd[i].n){
                sum=(sum+getC(l-1,r))*chu%mod;
                l--;
        }
            while(rsetd[i].m){
                sum=(sum-getC(l,r)+mod)%mod;
                r--;
            }
            ans[setd[i].id]=sum%mod;
        }
        for(LL i=1;i<=t;i++)
        printf("%lld\n",ans[i]);
    }
}

 

你可能感兴趣的:(莫队,算法)