[HDU6333]Problem B. Harvest of Apples

题目

传送门 to HDU

思路

打出这两个字,一切都结束了:莫队

大家都会了。但是很难往这个方向去想。多数童鞋肯定是想用 log ⁡ \log log 解决问题,用数学方法计算。

代码

#include 
#include 
#include 
#include 
using namespace std;
inline int readint(){
     
	int a = 0; char c = getchar(), f = 1;
	for(; c<'0'||c>'9'; c=getchar())
		if(c == '-') f = -f;
	for(; '0'<=c&&c<='9'; c=getchar())
		a = (a<<3)+(a<<1)+(c^48);
	return a*f;
}

const int MaxN = 100005;
const int Mod = 1e9+7;
int jc[MaxN], inv[MaxN];
void prepare(){
     
	jc[1] = inv[1] = 1;
	for(int i=2; i<MaxN; ++i){
     
		jc[i] = 1ll*jc[i-1]*i%Mod;
		inv[i] = (0ll+Mod-Mod/i)
			* inv[Mod%i]%Mod;
	}
	for(int i=2; i<MaxN; ++i)
		inv[i] = 1ll*inv[i-1]*inv[i]%Mod;
	jc[0] = inv[0] = 1;
}
long long C(int n,int m){
     
	return 1ll*jc[n]*inv[m]%Mod*inv[n-m]%Mod;
}

const int Block = 330;
struct Query{
     
	int l, r, id;
	bool operator < (const Query &t) const {
     
		if(l/Block != t.l/Block)
			return l/Block < t.l/Block;
		return r < t.r;
	}
};
Query ask[MaxN];
int res[MaxN];

int main(){
     
	prepare();
	int q = readint();
	for(int i=1; i<=q; ++i){
     
		ask[i].l = readint();
		ask[i].r = readint();
		ask[i].id = i;
	}
	sort(ask+1,ask+q+1);
	int nowl = 0, nowr = 0;
	int ans = 1; // C(0,0)=1
	for(int i=1; i<=q; ++i){
     
		while(nowl < ask[i].l){
     
			ans = (Mod-C(nowl,nowr)+(ans<<1))%Mod;
			++ nowl;
		}
		while(nowr > ask[i].r){
     
			ans = (ans+Mod-C(nowl,nowr))%Mod;
			-- nowr;
		}
		while(nowl > ask[i].l){
     
			ans = (ans+C(-- nowl,nowr))%Mod;
			ans = 1ll*ans*inv[2]%Mod;
		}
		while(nowr < ask[i].r)
			ans = (ans+C(nowl,++ nowr))%Mod;
		res[ask[i].id] = ans;
	}
	for(int i=1; i<=q; ++i)
		printf("%d\n",res[i]);
	return 0;
}

你可能感兴趣的:(C++,莫队,数学)