kdtree板子题
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;
const long double eps = 1e-14;
const int maxn = 2e5+10;
int idx, k=2, n;
struct node {
int x[2], c, id;
void read(int _id) {
scanf("%d%d%d", x, x+1, &c);
id = _id;
}
bool operator < (const node &p) const { return x[idx] < p.x[idx]; }
}point[maxn];
typedef pair<long double, node> tp;
tp Q;
struct KdTree {
node tr[maxn<<2];
int son[maxn<<2];
#define ls (rt<<1)
#define rs (rt<<1|1)
void build(int l, int r, int rt = 1, int dep = 0) {
if(l > r) return;
son[rt] = r-l;
son[ls] = son[rs] = -1;
idx = dep%k;
int mid = l + r >> 1;
nth_element(point+l, point+mid, point+r+1);
tr[rt] = point[mid];
build(l, mid-1, ls, dep+1);
build(mid+1, r, rs, dep+1);
}
void query(const node &p, int rt = 1, int dep = 0) {
if(son[rt] == -1) return;
tp nd(0, tr[rt]);
for (int i = 0; i < k; ++i)
nd.first += (long double)(tr[rt].x[i]-p.x[i])*(tr[rt].x[i]-p.x[i]);
int dim = dep % k, x = ls, y = rs, fg = 0;
if(p.x[dim] >= tr[rt].x[dim]) swap(x, y);
if(~son[x]) query(p, x, dep+1);
if(Q.first == -1) {
if(tr[rt].c <= p.c) Q = nd;
fg = 1;
} else {
if(tr[rt].c <= p.c && (nd.first < Q.first || (fabs(nd.first-Q.first)<eps && nd.second.id < Q.second.id)))
Q = nd;
if((long double)(p.x[dim]-tr[rt].x[dim])*(p.x[dim]-tr[rt].x[dim]) < Q.first)
fg = 1;
}
if(~son[y] && fg) query(p, y, dep+1);
}
}kd;
int T, q;
int main() {
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &q);
for (int i = 1; i <= n; ++i)
point[i].read(i);
kd.build(1, n);
while(q--) {
Q.first = -1;
node tmp;
for (int j = 0; j < k; ++j) scanf("%d", &tmp.x[j]); scanf("%d", &tmp.c);
kd.query(tmp);
tmp = Q.second;
printf("%d %d %d\n", tmp.x[0], tmp.x[1], tmp.c);
}
}
return 0;
}
hdu 5992 Finding Hotels (kdTree)
原文:https://www.cnblogs.com/acerkoo/p/11674328.html