每一个点有三个属性:(x,y,c)
每次查询要在log的时间内完成,查找距离(x,y)点最近的已知点,并且已知点的花费c要小于等于给定的一个数。
一开始想,如果直接用二维的kdtree来做,直接在query找的时候忽略花费>c的点不就好了,但是发现这样不满足kdtree BST的性质,是没有办法往下走的。那就得考虑把c也作为一维坐标,所以应该是三维kdtree.
可以手动定义如果花费大于c,那么距离看成无穷大(kdtree中经常可以这样来忽略一个管辖范围内都不合格的点,或者一个单独的点)
如果考虑不用>c的点来更新答案的话,也可以用二维kdtree来做,毕竟题目没有说要求花费也最小。但是这样没有剪枝。
感觉kdtree就是个大暴力,分治+搜索+剪枝
#include <bits/stdc++.h>
using namespace std;
#define N 200010
#define sqr(x) (x)*(x)
#define INF 4e10+1
typedef long long LL;
LL x,y,ans;
int cmp_d;
int T,n,m,c,root;
int pos;
struct node
{
int l,r;
LL Min[2], Max[2], d[2];
int id,c;
}tr[N];
inline bool cmp(node a, node b)
{
return a.d[cmp_d] < b.d[cmp_d] || a.d[cmp_d] == b.d[cmp_d] && a.d[cmp_d^1] < b.d[cmp_d^1];
}
void updata(int p, int s)
{
if (!s) return ;
for (int i=0;i<=1;i++)
{
tr[p].Min[i] = min(tr[p].Min[i], tr[s].Min[i]);
tr[p].Max[i] = max(tr[p].Max[i], tr[s].Max[i]);
}
}
int build(int l, int r, int D)
{
cmp_d = D;
int mid = (l + r) >> 1;
nth_element(tr+l+1, tr+mid+1, tr+r+1, cmp);
tr[mid].l = tr[mid].r = 0;//多组数据
tr[mid].Min[0] = tr[mid].Max[0] = tr[mid].d[0];
tr[mid].Min[1] = tr[mid].Max[1] = tr[mid].d[1];
if (l != mid) tr[mid].l = build(l, mid-1, D^1);
if (r != mid) tr[mid].r = build(mid+1, r, D^1);
updata(mid, tr[mid].l);
updata(mid, tr[mid].r);
return mid;
}
LL dist(int p, LL x, LL y)
{
return (tr[p].d[0] - x) * (tr[p].d[0] - x) + (tr[p].d[1] - y) * (tr[p].d[1] - y);
}
LL getdis(int p, LL x, LL y)
{
LL res = 0;
if (x < tr[p].Min[0]) res += sqr(tr[p].Min[0] - x);
if (x > tr[p].Max[0]) res += sqr(x - tr[p].Max[0]);
if (y < tr[p].Min[1]) res += sqr(tr[p].Min[1] - y);
if (y > tr[p].Max[1]) res += sqr(y - tr[p].Max[1]);
return res;
}
void query(int p)
{
LL dl, dr, d0;
d0 = dist(p, x, y);
if (tr[p].c > c) d0 = INF;//单独去掉一个点,即不用这个点更新答案
//cout<<p<<' '<<tr[p].d[0]<<' '<<tr[p].d[1]<<' '<<tr[p].c<<' '<<d0<<' '<<ans<<endl;
if (ans > d0 || ans == d0 && tr[p].id < tr[pos].id){ans = d0;pos = p;}//记录点的编号
if (tr[p].l) dl = getdis(tr[p].l, x, y); else dl = INF;
if (tr[p].r) dr = getdis(tr[p].r, x, y); else dr = INF;
if (dl < dr)
{
if (dl <= ans && dl < INF) query(tr[p].l);
if (dr <= ans && dr < INF) query(tr[p].r);
}
else
{
if (dr <= ans && dr < INF) query(tr[p].r);
if (dl <= ans && dl < INF) query(tr[p].l);
}
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
for (int i=1;i<=n;i++)
{
scanf("%lld%lld%d", &tr[i].d[0], &tr[i].d[1], &tr[i].c);
tr[i].id = i;
}
root = build(1,n,0);
for (int i=1;i<=m;i++)
{
scanf("%lld%lld%d", &x, &y, &c);
ans = INF;
pos = 0;
query(root);
printf("%lld %lld %d\n", tr[pos].d[0], tr[pos].d[1], tr[pos].c);
}
}
}