HDU 6333 Problem B. Harvest of Apples(莫对算法)

Problem B. Harvest of Apples

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


 

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

 

思路:
S(n+1,m)=2*S(n,m)-C(n,m);S(n,m+1)=S(n,m)+C(n,m+1)。
离线,莫对算法处理。

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=1e9+7;
const int maxn=1e5+10;
ll fac[maxn],inv[maxn],ans[maxn];
struct node
{
    int n,m,id;
};
vector<node>G[maxn];
bool cmp(const node &a,const node &b){return a.n<b.n;}
ll pow1(ll a,ll b)
{
    ll r=1;
    while(b)
    {
        if(b&1) r=r*a%mod;
        a=a*a%mod;
        b/=2;
    }
    return r;
}
void init()
{
    fac[0]=1;
    for(ll i=1;i<maxn;i++) fac[i]=fac[i-1]*i%mod;
    inv[maxn-1]=pow1(fac[maxn-1],mod-2);
    for(ll i=maxn-2;i>=0;i--) inv[i]=inv[i+1]*(i+1)%mod;
}
ll C(int n,int m)
{
    return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
int main()
{
    init();
    int T;scanf("%d",&T);
    int unit=sqrt(maxn);
    for(int i=1;i<=T;i++)
    {
        node e;e.id=i;
        scanf("%d%d",&e.n,&e.m);
        G[e.m/unit+1].push_back(e);
    }
    for(int i=1;i<=unit+2;i++)
    {
        int len=G[i].size();
        if(!len)continue;
        sort(G[i].begin(),G[i].end(),cmp);
        int x=G[i][0].n,y=0;
        ll cnt=1;
        for(int j=0;j<G[i].size();j++)
        {
            node e=G[i][j];
            while(x<e.n) cnt=(2*cnt-C(x++,y)+mod)%mod;
            while(y<e.m) cnt=(cnt+C(x,++y))%mod;
            while(y>e.m) cnt=(cnt-C(x,y--)+mod)%mod;
            ans[e.id]=cnt;
        }
    }
    for(int i=1;i<=T;i++)
        printf("%lld\n",ans[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/81349575