【模板】kd树

题解

浅谈偏序问题与K-D Tree


题目

板子1 - P1429 平面最近点对(加强版)

板子2 - P4169 [Violet]天使玩偶/SJY摆棋子

板子3 - 2016ACM/ICPC亚洲区青岛站-重现赛(感谢中国石油大学) · Finding Hotels


板子1

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m, k;

namespace K_D_Tree {

    typedef double dbl;
    const int D = 2;// 空间维度
    int f = 0;//当前遍历到的维度 在kd树建树时相邻层的判断大小的维度是不一样的 x->y->x...

    struct Point {
        dbl d[D];//维度信息 第0维:x,第1维:y,第2维:z....

        // Point[x] = Point.d[x]
        // 不过 struct Point 内部无法使用
        dbl &operator[](const int x) {
            return d[x];
        }

        void read() {
            for (int i = 0; i < D; i++) {
                cin >> d[i];
            }
        }

        bool operator==(const Point &other) {
            for (int i = 0; i < D; i++) {
                if (d[i] != other.d[i]) {
                    return false;
                }
            }
            return true;
        }

        bool operator<(const Point &other) const {
            if (d[f] != other.d[f]) {
                return d[f] < other.d[f]; // 根据当前要求的维度进行排序 用于nth_element()排序中
            }
            // 如果 d[f]==other[f] 就按照维度 找到第一个不相同的维度
            for (int i = 0; i < D; i++) {
                if (i ^ f && d[i] != other.d[i])
                    return d[i] < other.d[i];
            }
            return false;// 到这里其实就是两个重合的点
        }

        //D=2时的构造函数
        Point(dbl x = 0, dbl y = 0) {
            d[0] = x, d[1] = y;
        }

    } p[N]; // 这里的数组p用来存储题目给出的点的信息

    // 求两点距离的平方
#define sqr(x) (pow((x),2.0))

    dbl dis2(Point a, Point b) {
        dbl res = 0.0;
        for (int i = 0; i < D; i++) {
            res += sqr(a[i] - b[i]);
        }
        return res;
    }

    struct KDTree {
    private:
        struct Node {
            Node *son[2];//左右儿子节点
            Point p;// 当前节点存储的点
            Point Min, Max; // 以当前节点为根的子树所代表的矩阵的左下角和右上角

            void pushUp() {//更新儿子传上来的信息 维护子树所代表的矩阵范围
                for (int i = 0; i < D; i++) {
                    Min[i] = min(p[i], min(son[0]->Min[i], son[1]->Min[i]));
                    Max[i] = max(p[i], max(son[0]->Max[i], son[1]->Max[i]));
                }
            }

            // 估值函数 判断目标点到当前矩阵的最短曼哈顿距离的平方
            dbl f(Point x) {
                dbl res = 0.0;
                for (int i = 0; i < D; i++) {
                    res += sqr(max(Min[i] - x[i], 0.0)) + sqr(max(x[i] - Max[i], 0.0));
                }
                return res;
            }

        } *tail, *null, *root, MemoryPool[N];
        // tail - 指向当前存储的最后一个节点的后一个位置
        // null - 自定义的空指针(Min、Max有限定) 注意与NULL的区分
        // MemoryPool - 又找了个空间存之前读入的数组p

        void init() {
            tail = MemoryPool;
            null = tail++;
            null->son[0] = null->son[1] = null;// 都是指向null的
            // null的特殊赋值
            for (int i = 0; i < D; i++) {
                null->Min[i] = DBL_MAX;
                null->Max[i] = DBL_MIN;
            }
            root = null;
        }

        Node *creatNode(Point x) {
            Node *o = tail++;
            o->p = o->Max = o->Min = x;
            o->son[0] = o->son[1] = null;
            return o;
        }

        //根据第d维 对 p[l..r] 内的点进行建树 返回树的根节点
        Node *build(int l, int r, int d) {
            if (l > r) return null;
            int mid = l + r >> 1;
            f = d;
            // 百度nth_element用法
            // 只有p[mid]是在正确的位置上
            nth_element(p + l, p + mid, p + r + 1);
            Node *o = creatNode(p[mid]);//找到中位数
            if (l == r) return o;
            o->son[0] = build(l, mid - 1, (d + 1) % D);
            o->son[1] = build(mid + 1, r, (d + 1) % D);
            o->pushUp();
            return o;
        }

        // 求平面上最近点对
        // 遍历每个点x 在k-d-tree里找关于x的最近点
        void queryNearestPointByX(Node *o, const Point &x) {
            ans = min(ans, (Point) x == o->p ? DBL_MAX : dis2(o->p, x));//如果搜到了自己 则不能算入答案
            dbl F[2] = {DBL_MAX, DBL_MAX};//比较左右两棵子树的估值函数
            if (o->son[0] != null) {
                F[0] = o->son[0]->f(x);
            }
            if (o->son[1] != null) {
                F[1] = o->son[1]->f(x);
            }
            int now = F[0] >= F[1];
            // 减枝 如果估计值都比ans大 就没必要往下走
            if (F[now] < ans) {// 优先走较近的那个矩阵
                queryNearestPointByX(o->son[now], x);
            }
            now ^= 1;
            if (F[now] < ans) { // 然后再走另外一颗
                queryNearestPointByX(o->son[now], x);
            }
        }

    public:
        dbl ans = DBL_MAX;

        KDTree() { init(); }

        void build() {
            root = build(1, n, 0);
        }

        void queryNearestPointPair(Point &x) {
            queryNearestPointByX(root, x);
        }

    } kdt;
}
using namespace K_D_Tree;
map<Point, int> mp;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    for (int i = 1; i <= n; i++) {
        p[i].read();
        if (++mp[p[i]] > 1) {
            //有重叠点
            cout << fixed << setprecision(4) << 0.0 << endl;
            return 0;
        }
    }
    kdt.build();
    for (int i = 1; i <= n; i++) {
        kdt.queryNearestPointPair(p[i]);
    }
    
    cout << fixed << setprecision(4) << sqrt(kdt.ans) << endl;
    return 0;
}

板子2

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const double alpha = 0.75;

const int N = 6e5 + 10;
int n, m;

namespace K_D_Tree {

    typedef int dbl;
    const int D = 2;// 空间维度
    int f = 0;//当前遍历到的维度 在kd树建树时相邻层的判断大小的维度是不一样的 x->y->x...

    struct Point {
        int d[D];//维度信息 第0维:x,第1维:y,第2维:z....

        // Point[x] = Point.d[x]
        // 不过 struct Point 内部无法使用
        int &operator[](const int x) {
            return d[x];
        }

        void read() {
            for (int i = 0; i < D; i++) {
                cin >> d[i];
            }
        }

        bool operator==(const Point &other) {
            for (int i = 0; i < D; i++) {
                if (d[i] != other.d[i]) {
                    return false;
                }
            }
            return true;
        }

        bool operator<(const Point &other) const {
            if (d[f] != other.d[f]) {
                return d[f] < other.d[f]; // 根据当前要求的维度进行排序 用于nth_element()排序中
            }
            // 如果 d[f]==other[f] 就按照维度 找到第一个不相同的维度
            for (int i = 0; i < D; i++) {
                if (i ^ f && d[i] != other.d[i])
                    return d[i] < other.d[i];
            }
            return false;// 到这里其实就是两个重合的点
        }

        //D=2时的构造函数
        Point(int x = 0, int y = 0) {
            d[0] = x, d[1] = y;
        }

    } p[N]; // 这里的数组p用来存储题目给出的点的信息

    // 求两点的Manhattan距离
    int Manhattan(Point a, Point b) {
        int res = 0;
        for (int i = 0; i < D; i++) {
            res += abs(a[i] - b[i]);
        }
        return res;
    }

    struct KDTree {
    private:
        struct Node {
            Node *son[2];//左右儿子节点
            Point p;// 当前节点存储的点
            Point Min, Max; // 以当前节点为根的子树所代表的矩阵的左下角和右上角
            int size;//子树大小

            void pushUp() {//更新儿子传上来的信息 维护子树所代表的矩阵范围
                size = son[0]->size + 1 + son[1]->size;

                for (int i = 0; i < D; i++) {
                    Min[i] = min(p[i], min(son[0]->Min[i], son[1]->Min[i]));
                    Max[i] = max(p[i], max(son[0]->Max[i], son[1]->Max[i]));
                }
            }

            //失衡因子 用于判断是否需要重构
            bool unBalanced() {
                return (son[0]->size > size * alpha) || (son[1]->size > size * alpha);
            }

            // 估值函数 判断目标点到当前矩阵的最短曼哈顿距离
            int f(Point x) {
                int res = 0;
                for (int i = 0; i < D; i++) {
                    res += max(Min[i] - x[i], 0) + max(x[i] - Max[i], 0);
                }
                return res;
            }

        } *tail, *null, *root, MemoryPool[N], *Recycle[N];

        // tail - 指向当前存储的最后一个节点的后一个位置
        // null - 自定义的空指针(Min、Max有限定) 注意与NULL的区分
        // MemoryPool - 又找了个空间存之前读入的数组p
        // Recycle - 垃圾桶 存放回收重建的节点的地址 减少空间申请
        int top = 0;// *Recycle[top]
        int cnt = 0;// p[1...cnt] 回收的节点的个数 具体详见kd树重建部分


        void init() {
            tail = MemoryPool;
            null = tail++;
            null->son[0] = null->son[1] = null;// 都是指向null的
            // null的特殊赋值
            for (int i = 0; i < D; i++) {
                null->Min[i] = INT_MAX;
                null->Max[i] = INT_MIN;
            }
            root = null;
        }

        Node *createNode(Point x) {
            Node *o = top ? Recycle[--top] : tail++; 
            o->p = o->Max = o->Min = x;
            o->son[0] = o->son[1] = null;
            o->size = 1;
            return o;
        }


        //根据第d维 对 p[l..r] 内的点进行建树 返回树的根节点
        Node *build(int l, int r, int d) {
            if (l > r) return null;
            int mid = l + r >> 1;
            f = d;
            // 百度nth_element用法
            // 只有p[mid]是在正确的位置上
            nth_element(p + l, p + mid, p + r + 1);
            Node *o = createNode(p[mid]);//找到中位数
            if (l == r) return o;
            o->son[0] = build(l, mid - 1, (d + 1) % D);
            o->son[1] = build(mid + 1, r, (d + 1) % D);
            o->pushUp();
            return o;
        }

        int res;// 最近距离

        void queryMinDist(Node *o, Point &x) {
            res = min(res, Manhattan(o->p, x));
            int F[2] = {INT_MAX, INT_MAX};//左右两颗子树关于x的估值函数
            if (o->son[0] != null) {
                F[0] = o->son[0]->f(x);
            }
            if (o->son[1] != null) {
                F[1] = o->son[1]->f(x);
            }
            int now = F[0] >= F[1];//走估值函数小的那一棵子树
            if (F[now] < res) {
                queryMinDist(o->son[now], x);
            }
            now ^= 1;
            if (F[now] < res) {
                queryMinDist(o->son[now], x);
            }
        }

        //---- kd树重构 ----

        int rebuild_d = 0;// 树重构时选择的维度
        // Node* &  -> Node* 的引用类型
        // 返回要修改的子树的节点的地址 这样方便后面直接在原树上修改
        Node **insert(Node *&o, Point &x, int d) {
            if (o == null) {
                o = createNode(x);
                return &null;
            }
            // bad 最浅的失衡节点
            Node **bad = insert(o->son[o->p[d] < x[d]], x, (d + 1) % D);
            o->pushUp();
            if (o->unBalanced()) {
                bad = &o;
                rebuild_d = d;
            }
            return bad;
        }


        void travel(Node *o) {
            if (o == null) return;
            travel(o->son[0]);
            p[++cnt] = o->p;// 原先存放点的数组拿来存放要回收的点 (显然原数组就无法保存原来的信息了)
            Recycle[top++] = o;//保存地址 节省空间
            travel(o->son[1]);
        }

        void rebuild(Node *&o, int d) {
            cnt = 0;
            travel(o);//回收失衡节点及以子树里的节点
            o = build(1, cnt, d);// 对这一部分重建
            // 因为传入的是指针 修改后 节点o所在的这一棵子树与o父亲节点之间的关系没有发生改变
        }

    public:

        KDTree() { init(); }

        void build() {
            root = build(1, n, 0);
        }

        //查询关于x最近的点
        int query(Point x) {
            res = INT_MAX;
            queryMinDist(root, x);
            return res;
        }

        void insert(Point x) {
            Node **bad = insert(root, x, rebuild_d = 0);
            if (*bad == null) {
                // 没有失衡节点 不需要重建
                return;
            }
            // 直接从失衡节点开始修改 同时修改了整棵树
            rebuild(*bad, rebuild_d);
        }

    } kdt;
}
using namespace K_D_Tree;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        p[i].read();
    }
    kdt.build();
    int op, x, y;
    while (m--) {
        cin >> op >> x >> y;
        if (op == 1) {
            kdt.insert(Point(x, y));
        } else {
            cout << kdt.query(Point(x, y)) << endl;
        }
    }
    return 0;
}

板子3

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 8e5 + 10;
const int M = 2e4 + 10;
int n, m, k;

struct Hotel {
    ll x, y, c;
    int id;

    void read(int Id) {
        cin >> x >> y >> c;
        id = Id;
    }

    void put() {
        cout << x << " " << y << " " << c << endl;
    }

    bool operator<(const Hotel other) const {
        return c < other.c;
    }
} hotel[N], guest[M];

namespace K_D_Tree {
    const double alpha = 0.75;
    const int D = 2;
    int f = 0;

    struct Point {
        ll d[D];
        int id;

        Point() {}

        Point(Hotel hotel) {
            d[0] = hotel.x, d[1] = hotel.y;
            id = hotel.id;
        }

        ll &operator[](const int x) {
            return d[x];
        }

        bool operator<(const Point &other) const {
            if (d[f] != other.d[f]) {
                return d[f] < other.d[f]; // 根据当前要求的维度进行排序 用于nth_element()排序中
            }
            // 如果 d[f]==other[f] 就按照维度 找到第一个不相同的维度
            for (int i = 0; i < D; i++) {
                if (i ^ f && d[i] != other.d[i])
                    return d[i] < other.d[i];
            }
            return id < other.id;
        }

    } point[N];

#define pow2(x) ((x)*(x))

    ll dis2(Point a, Point b) {
        ll res = 0;
        for (int i = 0; i < D; i++) {
            res += pow2(a[i] - b[i]);
        }
        return res;
    }


    struct KDTree {

    private:
        struct Node {
            Point p, Min, Max;
            Node *son[2];
            int size;

            void pushUp() {
                size = son[0]->size + 1 + son[1]->size;
                for (int i = 0; i < D; i++) {
                    Min[i] = min(p[i], min(son[0]->Min[i], son[1]->Min[i]));
                    Max[i] = max(p[i], max(son[0]->Max[i], son[1]->Max[i]));
                }
            }

            bool unbalanced() {
                return (son[0]->size > alpha * size) || (son[1]->size > alpha * size);
            }

            ll f(Point x) {
                ll res = 0;
                for (int i = 0; i < D; i++) {
                    res += pow2(max(Min[i] - x[i], 0ll)) + pow2(max(x[i] - Max[i], 0ll));
                }
                return res;
            }


        } *null, *tail, MemoryPool[N], *root, *Recycle[N];

        int cnt, top;

        void init() {
            tail = MemoryPool;
            null = tail++;
            null->son[0] = null->son[1] = null;
            for (int i = 0; i < D; i++) {
                null->Min[i] = LONG_LONG_MAX;
                null->Max[i] = LONG_LONG_MIN;
            }
            root = null;
            f = 0;
        }

        Node *createNode(Point x) {
            Node *o = top ? Recycle[--top] : tail++;
            o->p = o->Max = o->Min = x;
            o->son[0] = o->son[1] = null;
            o->size = 1;
            return o;
        }

        int rebuild_d = 0;

        Node **insert(Node *&o, Point &x, int d) {
            if (o == null) {
                o = createNode(x);
                return &null;
            }

            Node **bad = insert(o->son[o->p[d] < x[d]], x, (d + 1) % D);
            o->pushUp();
            if (o->unbalanced()) {
                bad = &o;
                rebuild_d = d;
            }
            return bad;
        }

        void travel(Node *o) {
            if (o == null) return;
            travel(o->son[0]);
            point[++cnt] = o->p;
            Recycle[top++] = o;
            travel(o->son[1]);
        }

        Node *build(int l, int r, int d) {
            if (l > r) return null;
            int mid = l + r >> 1;
            f = d;
            nth_element(point + l, point + mid, point + 1 + r);
            Node *o = createNode(point[mid]);
            if (l == r) return o;
            o->son[0] = build(l, mid - 1, (d + 1) % D);
            o->son[1] = build(mid + 1, r, (d + 1) % D);
            o->pushUp();
            return o;
        }

        void rebuild(Node *&o, int d) {
            cnt = 0;
            travel(o);
            o = build(1, cnt, d);
        }

        ll Dist;
        int res;

        void queryMinDist(Node *&o, Point &x) {
            ll dist = dis2(o->p, x);
            if (dist < Dist || (dist == Dist && o->p.id < res)) {
                Dist = dist;
                res = o->p.id;
            }

            ll F[2] = {LONG_LONG_MAX, LONG_LONG_MAX};
            if (o->son[0] != null) F[0] = o->son[0]->f(x);
            if (o->son[1] != null) F[1] = o->son[1]->f(x);
            int now = F[0] > F[1];
            if (F[now] <= Dist) {
                queryMinDist(o->son[now], x);
            }
            now ^= 1;
            if (F[now] <= Dist) {
                queryMinDist(o->son[now], x);
            }
        }

    public:
        KDTree() { init(); }

        void clear() { init(); }

        void insert(Point x) {
            Node **bad = insert(root, x, rebuild_d = 0);
            if (*bad == null) {
                return;
            }
            rebuild(*bad, rebuild_d);
        }

        int query(Point x) {
            Dist = LONG_LONG_MAX;
            res = INT_MAX;
            queryMinDist(root, x);
            return res;
        }
    } kdt;
}
using namespace K_D_Tree;

int res[N];


int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    int T;
    cin >> T;
    for (int cs = 1; cs <= T; cs++) {
        cin >> n >> m;

        for (int i = 1; i <= n; i++) {
            hotel[i].read(i);
            hotel[i + n] = hotel[i];
        }
        for (int i = 1; i <= m; i++) {
            guest[i].read(i);
        }

        sort(hotel + 1, hotel + 1 + n);
        sort(guest + 1, guest + 1 + m);

        for (int i = 1, j = 1; i <= m; i++) {
            while (j <= n && hotel[j].c <= guest[i].c) {
                kdt.insert(Point(hotel[j++]));
            }
            res[guest[i].id] = kdt.query(guest[i]) + n;
        }
        for (int i = 1; i <= m; i++) {
            hotel[res[i]].put();
        }

        kdt.clear();
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值