您的位置:首页 > 其它

[KD-TREE] BZOJ 4066 简单题

2016-05-18 18:25 337 查看
题意:二维平面内单点加 范围求和

强制在线 CDQ就比较难过了

kd树好神 参考了黄学长的模板

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;

inline char nc()
{
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}

inline void read(int &x)
{
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=200005;

int n,D;

struct node{
int d[2],mx[2],mn[2],l,r;
ll val,sum;
node(int x=0,int y=0,int v=0) { mx[0]=mn[0]=d[0]=x; mx[1]=mn[1]=d[1]=y; l=r=0; val=sum=v; }
int& operator[](int x) { return d[x]; }
friend bool operator == (const node &A, const node &B) { return A.d[0]==B.d[0] && A.d[1]==B.d[1]; }
friend bool operator < (const node &A,const node &B) { return A.d[D]<B.d[D]; }
}tmp
;

inline bool inside(int x1,int y1,int x2,int y2,int X1,int Y1,int X2,int Y2){
return X1<=x1 && x2<=X2 && Y1<=y1 && y2<=Y2;
}

inline bool outside(int x1,int y1,int x2,int y2,int X1,int Y1,int X2,int Y2){
return x2<X1 || x1>X2 || y1>Y2 || y2<Y1;
}

struct KDT{
node T
,now;
int root,ncnt;
void update(int x){
int l=T[x].l,r=T[x].r;
for(int i=0;i<2;i++)
{
T[x].mn[i]=T[x].mx[i]=T[x][i];
if(l) T[x].mn[i]=min(T[x].mn[i],T[l].mn[i]),T[x].mx[i]=max(T[x].mx[i],T[l].mx[i]);
if(r) T[x].mn[i]=min(T[x].mn[i],T[r].mn[i]),T[x].mx[i]=max(T[x].mx[i],T[r].mx[i]);
}
T[x].sum=T[x].val+T[l].sum+T[r].sum;
}
void Ins(int &x,int D){
if (!x){
T[x=++ncnt]=now; return;
}
if (now==T[x]){
T[x].val+=now.val; T[x].sum+=now.val; return;
}
if (now[D]<T[x][D]) Ins(T[x].l,D^1); else Ins(T[x].r,D^1);
update(x);
}
ll Query(int x,int X1,int Y1,int X2,int Y2){
if (!x) return 0; ll ret=0;
if (outside(T[x].mn[0],T[x].mn[1],T[x].mx[0],T[x].mx[1],X1,Y1,X2,Y2)) return 0;
if (inside(T[x].mn[0],T[x].mn[1],T[x].mx[0],T[x].mx[1],X1,Y1,X2,Y2)) return T[x].sum;
if (inside(T[x][0],T[x][1],T[x][0],T[x][1],X1,Y1,X2,Y2)) ret+=T[x].val;
return ret+Query(T[x].l,X1,Y1,X2,Y2)+Query(T[x].r,X1,Y1,X2,Y2);
}
int Reb(int l,int r,int D){
if (l>r) return 0;
int mid=(l+r)>>1;
::D=D; nth_element(tmp+l,tmp+mid,tmp+r+1);
T[mid]=tmp[mid];
T[mid].l=Reb(l,mid-1,D^1);
T[mid].r=Reb(mid+1,r,D^1);
update(mid); return mid;
}
}KD;

ll lastans;

int main()
{
int order,X1,X2,Y1,Y2,x,y,a,B=10000;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(n);
while (1){
read(order);
if (order==3)
break;
else if (order==1)
{
read(x); read(y); read(a);
x^=lastans; y^=lastans; a^=lastans;
KD.now=node(x,y,a);
KD.Ins(KD.root,0);
if (KD.ncnt==B)
{
for(int i=1;i<=KD.ncnt;i++) tmp[i]=KD.T[i];
KD.root=KD.Reb(1,KD.ncnt,0); B+=10000;
}
}
else if (order==2)
{
read(X1); read(Y1); read(X2); read(Y2);
X1^=lastans; Y1^=lastans; X2^=lastans; Y2^=lastans;
printf("%lld\n",lastans=KD.Query(KD.root,X1,Y1,X2,Y2));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: