【BOI2007】Mokia 摩基亚

本文介绍了一种使用CDQ分治解决二维树状数组问题的方法,通过将询问拆分为四个前缀和并应用容斥原理来统计答案。文章详细解释了如何在时间、左边界、右边界三个维度上进行操作,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

CDQ分治板子题

其实和陌上花开差不多

把时间、 l 、 r l、r lr看成三个维度

像二维树状数组统计一样,把每一个询问拆成四块前缀和相减

然后统计答案的时候容斥一下

那么现在需要考虑的就只有 l , r l,r l,r

由于时间自然有序,就只需要考虑二维了

直接上 C D Q CDQ CDQ

注意树状数组空间开到 2 e 6 2e6 2e6

#include<bits/stdc++.h>
using namespace std;
inline int read(){
	char ch=getchar();
	int res=0,f=1;
	while(!isdigit(ch)){if(ch=='-')f=-f;ch=getchar();}
	while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48),ch=getchar();
	return res*f;
}
const int N=500005;
struct ask{
	int l,r,pos,op;
}q1[N],a[N];
int s,n,tot,cnt,ans[N],tr[2000000];
inline int lowbit(int x){return (x&(-x));}
inline void update(int pos,int k){for(;pos<=n;pos+=lowbit(pos))tr[pos]+=k;}
inline int query(int pos,int res=0){for(;pos;pos-=lowbit(pos))res+=tr[pos];return res;}
#define mid ((l+r)>>1)
inline bool comp(const ask&a,const ask&b){
	if(a.l==b.l)return a.r<b.r;
	return a.l<b.l;
}
inline void cdq(int l,int r){
	if(l==r)return;
	cdq(l,mid),cdq(mid+1,r);
	sort(a+l,a+mid+1,comp);
	sort(a+mid+1,a+r+1,comp);
	int i=l;
	for(int j=mid+1;j<=r;j++){
		for(;i<=mid&&a[i].l<=a[j].l;i++)
			if(a[i].op==1)update(a[i].r,a[i].pos);
		if(a[j].op==2)ans[a[j].pos]+=query(a[j].r);
	}
	for(int j=l;j<i;j++)if(a[j].op==1)update(a[j].r,-a[j].pos);
}
#undef mid
int main(){
	s=read(),n=read();
	int op=read();
	while(op!=3){
		if(op==1){
			a[++tot].l=read(),a[tot].r=read(),a[tot].pos=read(),a[tot].op=1;
		}
		else{
			int x1=read(),y1=read(),x2=read(),y2=read();
			a[++tot].l=x2  ,a[tot].r=y2  ,a[tot].pos=++cnt,a[tot].op=2;
			a[++tot].l=x1-1,a[tot].r=y2  ,a[tot].pos=++cnt,a[tot].op=2;
			a[++tot].l=x2  ,a[tot].r=y1-1,a[tot].pos=++cnt,a[tot].op=2;
			a[++tot].l=x1-1,a[tot].r=y1-1,a[tot].pos=++cnt,a[tot].op=2;
		}
		op=read();
	}
	cdq(1,tot);
	for(int i=1;i<=cnt;i+=4){
		cout<<(ans[i]-ans[i+1]-ans[i+2]+ans[i+3])<<'\n';
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值