hdu 6333 Problem B. 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 109+7.


Sample Input

2 5 2 1000 500


Sample Output

16         924129523


题意很简单:

    从 n 中选出至多 m 个有多少种方法。

也就是求 C(0,n) + C(1,n)+ ........+ C(m ,n) 

思路 :

    首先暴力肯定是过不了的。

首先从杨辉三角中我们不难发现每个数都是上面两个数之和,于是经过简单推倒得出S(n ,m )  = 2 * S ( n - 1,m )  -  C(n - 1,m)

还有容易证得 S(n ,m - 1) + C(n, m ) = S(n ,m)  (((其中S(n ,m ) = C ( n, 0 )+ .......+ C ( n , m ) 。 ))) ,由 区间 [  n , m ] 可以 O(n ) 求出   [  n , m  + 1 ] 、[  n - 1, m  ] 、[  n  + 1, m   ] 、[  n , m  - 1 ] 我们可以考虑用莫队算法 。

注意求 C (n , m ) 时要用逆元来求.

代码如下 :

#include
using namespace std;
typedef long long ll;
#define bug printf("******************\n");
const int mod = 1e9 + 7;
const int maxn = 1e5 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f;

int t ,block;
ll sum;
ll a[maxn],b[maxn];

struct node{
	int l,r,id;
	ll ans;
	bool operator < (const node &x) const {
		return (l - 1) / block == (x.l - 1) / block ? r < x.r : l < x.l;
	} 
}ask[maxn];

ll Mod_Pow(ll x,ll n){
	ll res = 1;
	while(n > 0){
		if(n & 1) res = res * x % mod;
		x = x * x % mod;
		n >>= 1;
	}
	return res;
}

void init() {
    a[1] = 1;
    for(int i = 2; i < maxn; i++) a[i] = a[i-1] * i % mod;
    for(int i = 1; i < maxn; i++) b[i] = Mod_Pow(a[i], mod - 2);
}

ll C(int n,int m){
	if(n < 0 || m < 0 || m > n) return 0;
	if(m == 0 || m == n) return 1;
	return a[n] * b[n - m] % mod * b[m] % mod;
}

int main(){
	init();
	scanf("%d",&t);
	block = sqrt(maxn);
	sum = 1;
	for(int i = 1;i <= t;i++){
		scanf("%d %d",&ask[i].l,&ask[i].r);
		ask[i].id = i;
	}
	sort(ask + 1,ask + t + 1);
	for(int i = 1, l = 1, r = 0; i <= t; i++) {
		while(l < ask[i].l) sum = (2 * sum - C(l++, r) + mod) % mod;
		while(l > ask[i].l) sum = ((sum + C(--l, r)) * b[2]) % mod;
		while(r < ask[i].r) sum = (sum + C(l, ++r)) % mod;
		while(r > ask[i].r) sum = (sum - C(l, r--) + mod) % mod;
		ask[ask[i].id].ans = sum;
	}
	for(int i = 1;i <= t;i++){
		printf("%lld\n",ask[i].ans);
	}
	return 0;
}

 

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