题目链接:bzoj2468 SJY摆棋子
思路:黑棋子插入到kd_Tree中,白棋子跳过。
/**************************************************************
Problem: 2648
User: Revincent
Language: C++
Result: Accepted
Time:13984 ms
Memory:63324 kb
****************************************************************/
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define N 500005
#define inf 0x3f3f3f3f
using namespace std;
int root,d;
int Min,Max;
int n,m,op,x,y;
int ans;
struct node
{
int l,r,xy[2],Max[2],Min[2];
friend bool operator < (node a, node b)
{
if(a.xy[d] == b.xy[d])
return a.xy[d^1] < b.xy[d^1];
return a.xy[d] < b.xy[d];
}
} kd_tree[N<<2],_new;
void push_up(int rt, node a)
{
kd_tree[rt].Min[0] = min(kd_tree[rt].Min[0], a.Min[0]);
kd_tree[rt].Max[0] = max(kd_tree[rt].Max[0], a.Max[0]);
kd_tree[rt].Min[1] = min(kd_tree[rt].Min[1], a.Min[1]);
kd_tree[rt].Max[1] = max(kd_tree[rt].Max[1], a.Max[1]);
}
int build(int l, int r, int o)
{
int mid = (l + r) >> 1;
d = o;
nth_element(kd_tree+l, kd_tree+mid, kd_tree+r+1);
for(int i = 0; i < 2; ++i)
kd_tree[mid].Min[i] = kd_tree[mid].Max[i] = kd_tree[mid].xy[i];
kd_tree[mid].l = kd_tree[mid].r = 0;
if(l < mid)kd_tree[mid].l = build(l, mid-1, o^1);
if(r > mid)kd_tree[mid].r = build(mid+1, r, o^1);
if(kd_tree[mid].l)push_up(mid, kd_tree[kd_tree[mid].l]);
if(kd_tree[mid].r)push_up(mid, kd_tree[kd_tree[mid].r]);
return mid;
}
void _insert(int rt, int o)
{
if(_new.xy[o] >= kd_tree[rt].xy[o])
{
if(kd_tree[rt].r)
_insert(kd_tree[rt].r, o^1);
else
{
kd_tree[rt].r = ++n;
kd_tree[n] = _new;
}
}
else
{
if(kd_tree[rt].l)
_insert(kd_tree[rt].l, o^1);
else
{
kd_tree[rt].l = ++n;
kd_tree[n] = _new;
}
}
if(kd_tree[rt].l)push_up(rt, kd_tree[kd_tree[rt].l]);
if(kd_tree[rt].r)push_up(rt, kd_tree[kd_tree[rt].r]);
}
int get_min(node a)
{
int res = 0;
if(x > a.Max[0])res += x - a.Max[0];
if(x < a.Min[0])res += a.Min[0] - x;
if(y > a.Max[1])res += y - a.Max[1];
if(y < a.Min[1])res += a.Min[1] - y;
return res;
}
void query(int rt)
{
int dis = abs(kd_tree[rt].xy[0] - x) + abs(kd_tree[rt].xy[1] - y);
ans = min(ans, dis);
int lmin = inf,rmin = inf;
int l = kd_tree[rt].l,r = kd_tree[rt].r;
if(l)lmin = get_min(kd_tree[l]);
if(r)rmin = get_min(kd_tree[r]);
if(lmin < rmin)
{
if(lmin < ans)query(l);
if(rmin < ans)query(r);
}
else
{
if(rmin < ans)query(r);
if(lmin < ans)query(l);
}
}
int main()
{
scanf("%d%d", &n,&m);
for(int i = 1; i <= n; ++i)
scanf("%d%d", &kd_tree[i].xy[0],&kd_tree[i].xy[1]);
root = build(1, n, 0);
while(m--)
{
scanf("%d%d%d", &op,&x,&y);
if(op == 1)
{
_new.l = 0,_new.r = 0;
_new.xy[0] = _new.Min[0] = _new.Max[0] = x;
_new.xy[1] = _new.Min[1] = _new.Max[1] = y;
_insert(root, 0);
}
else
{
ans = inf;
query(root);
printf("%d\n", ans);
}
}
return 0;
}