BZOJ4066:简单题
浅谈\(K-D\) \(Tree\):https://www.cnblogs.com/AKMer/p/10387266.html
题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=4066
裸的强制在线插入点,像替罪羊树那样重建不平衡的子树即可。在回收要重建的子树的节点的时候记得把结点信息初始化掉。
时间复杂度:\(O(n\sqrt{n})\)
空间复杂度:\(O(n)\)
代码如下:
#include <cstdio>
#include <algorithm>
using namespace std;
const double alpha=0.75;
const int maxn=2e5+5,inf=2e9;
bool need_rebuild;
int n,lstans,pps,x,y,A,x1,x2,y1,y2;
int read() {
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
return x*f;
}
struct kd_tree {
int id[maxn];
int tot,root,cnt;
struct point {
int c[2],mn[2],mx[2];
int val,sum,siz,ls,rs;
bool operator<(const point &a)const {
return c[pps]<a.c[pps];
}
}p[maxn],node[maxn];
void prepare() {
p[0].mn[0]=p[0].mn[1]=inf;
p[0].mx[0]=p[0].mx[1]=-inf;
}
void update(int u) {
int ls=p[u].ls,rs=p[u].rs;
p[u].siz=p[ls].siz+1+p[rs].siz;
p[u].sum=p[ls].sum+p[u].val+p[rs].sum;
for(int i=0;i<2;i++) {
int mn=min(p[ls].mn[i],p[rs].mn[i]);
p[u].mn[i]=min(p[u].c[i],mn);
int mx=max(p[ls].mx[i],p[rs].mx[i]);
p[u].mx[i]=max(p[u].c[i],mx);
}
}
void ins(int &u,int d) {
if(!u) {
u=++tot;need_rebuild=1;
p[u].mn[0]=p[u].mx[0]=p[u].c[0]=x;
p[u].mn[1]=p[u].mx[1]=p[u].c[1]=y;
p[u].val=p[u].sum=A,p[u].siz=1;return;
}
if(p[u].c[0]==x&&p[u].c[1]==y) {
p[u].val+=A,p[u].sum+=A;return;
}
int tmp=d?y:x;
if(tmp<p[u].c[d])ins(p[u].ls,d^1);
else ins(p[u].rs,d^1);
update(u);
}
void recycle(int u) {
if(!u)return;
int ls=p[u].ls,rs=p[u].rs;
p[u].siz=1,p[u].ls=p[u].rs=p[u].sum=0;
id[++cnt]=u,node[cnt]=p[u];
recycle(ls),recycle(rs);
}
int rebuild(int l,int r,int d) {
int mid=(l+r)>>1,u=id[mid];pps=d;
nth_element(node+l,node+mid,node+r+1);
p[u]=node[mid];
if(l<mid)p[u].ls=rebuild(l,mid-1,d^1);
if(r>mid)p[u].rs=rebuild(mid+1,r,d^1);
update(u);return u;
}
void check(int &u,int d) {
int siz1=p[p[u].ls].siz,siz2=p[p[u].rs].siz;
if(max(siz1,siz2)>1.0*p[u].siz*alpha) {
recycle(u),u=rebuild(1,cnt,d),cnt=0;return;
}
if(p[u].c[0]==x&&p[u].c[1]==y)return;
int tmp=d?y:x;
if(tmp<p[u].c[d])check(p[u].ls,d^1);
else check(p[u].rs,d^1);
}
void query(int u) {
if(!u)return;
if(x2<p[u].mn[0]||x1>p[u].mx[0])return;
if(y2<p[u].mn[1]||y1>p[u].mx[1])return;
bool bo1=(x1<=p[u].mn[0]&&p[u].mx[0]<=x2);
bool bo2=(y1<=p[u].mn[1]&&p[u].mx[1]<=y2);
if(bo1&&bo2) {lstans+=p[u].sum;return;}
bo1=(x1<=p[u].c[0]&&p[u].c[0]<=x2);
bo2=(y1<=p[u].c[1]&&p[u].c[1]<=y2);
if(bo1&&bo2)lstans+=p[u].val;
if(p[u].ls)query(p[u].ls);
if(p[u].rs)query(p[u].rs);
}
}T;
int main() {
n=read();T.prepare();
while(1) {
int opt=read();
if(opt==1) {
x=read()^lstans,y=read()^lstans,A=read()^lstans;
T.ins(T.root,0);if(need_rebuild)T.check(T.root,0);
}
if(opt==2) {
x1=read()^lstans,y1=read()^lstans;
x2=read()^lstans,y2=read()^lstans;
lstans=0,T.query(T.root),printf("%d\n",lstans);
}
if(opt==3)break;
}
return 0;
}