kd树 hdu2966 In case of failure

传送门:点击打开链接

题意:给n个点,求对于每个点到最近点的欧几里德距离的平方。

思路:看鸟神博客学kd树劲啊点击打开链接


kd树其实是暴力树,,真的。。

它把一个平面划分成了很多个小平面。每次划分的依据是平面中按x排序的点的中位数或者是按y排序的点的中位数。

建树的复杂度是稳定O(nlogn),但是查询就是大暴力了

把平面分成很多个小平面后,相当于在平面上搜索剪枝。

kd树是一颗二叉树,假如我要查找离(a,b)最近的点,先按照x和y的划分,从kd树根节点出发走到(a,b)所在的平面,然后这个平面中有一个点,通过这个点,就能大致确定最近点的半径范围了。再看这个圈是否和其他的平面有相交部分,如果有,同样的也访问其他平面部分(说白了就是暴搜,是不是很暴力。。

求第k近暂时还没学会,只学会了求最近。。

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout<<"["<<x<<"]"
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w+",stdout)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1e5 + 5;

struct Point {
    int xy[2], l, r, id;
    void read(int i) {
        id = i;
        scanf("%d%d", &xy[0], &xy[1]);
    }
} P[MX];
int cmpw; LL ans;
int idx[MX];

bool cmp(const Point &a, const Point &b) {
    return a.xy[cmpw] < b.xy[cmpw];
}
int build(int l, int r, int w) {
    int m = (l + r) >> 1; cmpw = w;
    nth_element(P + l, P + m, P + 1 + r, cmp);
    idx[P[m].id] = m;
    P[m].l = l != m ? build(l, m - 1, !w) : 0;
    P[m].r = r != m ? build(m + 1, r, !w) : 0;
    return m;
}
LL dist(LL x, LL y = 0) {
    return x * x + y * y;
}
void query(int rt, int w, LL x, LL y) {
    LL temp = dist(x - P[rt].xy[0], y - P[rt].xy[1]);
    if(temp) ans = min(ans, temp);
    if(P[rt].l && P[rt].r) {
        bool sign = !w ? (x <= P[rt].xy[0]) : (y <= P[rt].xy[1]);
        LL d = !w ? dist(x - P[rt].xy[0]) : dist(y - P[rt].xy[1]);
        query(sign ? P[rt].l : P[rt].r, !w, x, y);
        if(d < ans) query(sign ? P[rt].r : P[rt].l, !w, x, y);
    } else if(P[rt].l) query(P[rt].l, !w, x, y);
    else if(P[rt].r) query(P[rt].r, !w, x, y);
}

int main() {
    int T, n; //FIN;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++) P[i].read(i);
        int rt = build(1, n, 0);
        for(int i = 1; i <= n; i++) {
            ans = 1e18;
            query(rt, 0, P[idx[i]].xy[0], P[idx[i]].xy[1]);
            printf("%I64d\n", ans);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值