BZOJ - 2648 SJY摆棋子 (kd树)
kd树+插入操作
不知为啥我的常数纳么大,加了快读才过的┐(゚~゚)┌
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int N=1e6+10,inf=0x3f3f3f3f; 5 struct P {int x[2];} a[N],val[N]; 6 bool cmp1(P a,P b) {return a.x[0]<b.x[0];} 7 bool cmp2(P a,P b) {return a.x[1]<b.x[1];} 8 typedef bool (*f)(P,P); 9 f cmp[2]= {cmp1,cmp2}; 10 int ls[N],rs[N],mx[N][2],mi[N][2],n,m,rt,tot; 11 #define mid ((l+r)>>1) 12 int newnode(P p) { 13 int u=++tot; 14 ls[u]=rs[u]=0,val[u]=p; 15 for(int i=0; i<2; ++i)mx[u][i]=mi[u][i]=p.x[i]; 16 return u; 17 } 18 void pu(int u) { 19 for(int i=0; i<2; ++i) { 20 mx[u][i]=max(max(mx[ls[u]][i],mx[rs[u]][i]),val[u].x[i]); 21 mi[u][i]=min(min(mi[ls[u]][i],mi[rs[u]][i]),val[u].x[i]); 22 } 23 } 24 int dis(P a,P b) { 25 int ret=0; 26 for(int i=0; i<2; ++i)ret+=abs(a.x[i]-b.x[i]); 27 return ret; 28 } 29 int mind(int u,P p) { 30 if(!u)return inf; 31 int ret=0; 32 for(int i=0; i<2; ++i) { 33 if(p.x[i]>mx[u][i])ret+=p.x[i]-mx[u][i]; 34 else if(p.x[i]<mi[u][i])ret+=mi[u][i]-p.x[i]; 35 } 36 return ret; 37 } 38 void ins(int& u,P p,int f=0) { 39 if(!u) {u=newnode(p); return;} 40 ins(cmp[f](p,val[u])?ls[u]:rs[u],p,f^1),pu(u); 41 } 42 int qry(int u,P p) { 43 if(!u)return inf; 44 int ret=dis(val[u],p); 45 int dl=mind(ls[u],p),dr=mind(rs[u],p); 46 if(dl<dr) {if(dl<ret)ret=min(ret,qry(ls[u],p)); if(dr<ret)ret=min(ret,qry(rs[u],p));} 47 else {if(dr<ret)ret=min(ret,qry(rs[u],p)); if(dl<ret)ret=min(ret,qry(ls[u],p));} 48 return ret; 49 } 50 void build(int& u,int f=0,int l=1,int r=n) { 51 if(l>r) {u=0; return;} 52 nth_element(a+l,a+mid,a+r+1,cmp[f]); 53 u=newnode(a[mid]); 54 build(ls[u],f^1,l,mid-1),build(rs[u],f^1,mid+1,r),pu(u); 55 } 56 inline void read(int& x) { 57 x=0; 58 bool f=0; 59 char ch=getchar(); 60 while(ch<'0'||ch>'9')(ch=='-')&&(f=1),ch=getchar(); 61 while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); 62 f&&(x=-x); 63 } 64 int main() { 65 mx[0][0]=mx[0][1]=~inf,mi[0][0]=mi[0][1]=inf; 66 read(n),read(m); 67 for(int i=1; i<=n; ++i)read(a[i].x[0]),read(a[i].x[1]); 68 build(rt); 69 while(m--) { 70 P p; 71 int t; 72 read(t),read(p.x[0]),read(p.x[1]); 73 if(t==1)ins(rt,p); 74 else printf("%d\n",qry(rt,p)); 75 } 76 return 0; 77 }