BZOJ2648 SJY摆棋子(KD-Tree)

  板子题。

#include<iostream> 
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define N 1000010
#define inf 2000000000
char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<'0'||c>'9')) c=getchar();return c;}
int gcd(int n,int m){return m==0?n:gcd(m,n%m);}
int read()
{
    int x=0,f=1;char c=getchar();
    while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
    while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
    return x*f;
}
int n,m,root,cnt,c,ans;
struct point
{
    int d[2],tag;
    bool operator <(const point&a) const
    {
        return d[c]<a.d[c];
    }
}a[N];
struct KDTree{int ch[2],a[2][2],tag;point p;
}tree[N];
struct data{int op;point p;
}q[N];
inline int dis(point u,point v){return abs(u.d[0]-v.d[0])+abs(u.d[1]-v.d[1]);}
inline void chkmin(int &x,int y){x=min(x,y);}
inline void chkmax(int &x,int y){x=max(x,y);}
inline bool isin(point x,int a[2][2]){return a[0][0]<=x.d[0]&&a[0][1]>=x.d[0]&&a[1][0]<=x.d[1]&&a[1][1]>=x.d[1];}
inline int max(int x,int y,int z){return max(max(x,y),z);}
inline int guess(point x,int a[2][2]){return max(0,a[0][0]-x.d[0],x.d[0]-a[0][1])+max(0,a[1][0]-x.d[1],x.d[1]-a[1][1]);}
void build(int &k,int l,int r,int op)
{
    if (l>r) return;
    k=++cnt;c=op;int mid=l+r>>1;
    nth_element(a+l,a+mid,a+r+1);
    tree[k].p=a[mid],tree[k].tag=a[mid].tag,
    tree[k].a[0][0]=tree[k].a[0][1]=a[mid].d[0],
    tree[k].a[1][0]=tree[k].a[1][1]=a[mid].d[1];
    for (int i=l;i<=r;i++)
    chkmin(tree[k].a[0][0],a[i].d[0]),chkmax(tree[k].a[0][1],a[i].d[0]),
    chkmin(tree[k].a[1][0],a[i].d[1]),chkmax(tree[k].a[1][1],a[i].d[1]);
    build(tree[k].ch[0],l,mid-1,op^1);
    build(tree[k].ch[1],mid+1,r,op^1);
}
void ins(int k,point x)
{
    if (!k) return;
    if (tree[k].p.d[0]==x.d[0]&&tree[k].p.d[1]==x.d[1]) {tree[k].tag=1;return;}
    if (isin(x,tree[tree[k].ch[0]].a)) ins(tree[k].ch[0],x);
    if (isin(x,tree[tree[k].ch[1]].a)) ins(tree[k].ch[1],x);
}
void query(int k,point x)
{
    if (!k) return;
    if (tree[k].tag) chkmin(ans,dis(x,tree[k].p));
    int p=tree[k].ch[0],q=tree[k].ch[1],u=guess(x,tree[p].a),v=guess(x,tree[q].a);
    if (v<u) swap(p,q),swap(u,v);
    if (u<ans) query(p,x);
    if (v<ans) query(q,x);
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("bzoj2648.in","r",stdin);
    freopen("bzoj2648.out","w",stdout);
    const char LL[]="%I64d\n";
#else
    const char LL[]="%lld\n";
#endif
    n=read(),m=read();
    for (int i=1;i<=n;i++) a[i].d[0]=read(),a[i].d[1]=read(),a[i].tag=1;
    for (int i=1;i<=m;i++)
    {
        q[i].op=read(),q[i].p.d[0]=read(),q[i].p.d[1]=read();
        if (q[i].op==1) a[++n]=q[i].p;
    }
    build(root,1,n,0);
    for (int i=1;i<=m;i++)
    if (q[i].op==1) ins(root,q[i].p);
    else ans=inf,query(root,q[i].p),printf("%d\n",ans);
    return 0;
}

 

posted @ 2018-12-22 00:01  Gloid  阅读(123)  评论(0编辑  收藏  举报