• 简洁好用的KDTree模板


    看了好多人的模板以后写的,感觉这个非常优秀,代码短,空间小,特判少

    论哨兵节点的作用.jpg

    下面是BZOJ2716/2648的代码

    int n, m, x, y, now, ans, op, cnt, d[2];
    struct Node {
      int Min[2], Max[2], d[2];
      Node *ls, *rs;
      Node (const pii &a, Node *b) {
        Min[0] = Max[0] = d[0] = a.fi;
        Max[1] = Min[1] = d[1] = a.se;
        ls = rs = b;
      }
      Node () {}
      inline void pushup() {
        lop0(i, 2) Min[i] = min(d[i], min(ls->Min[i], rs->Min[i])), Max[i] = max(d[i], max(ls->Max[i], rs->Max[i]));
      }
      inline bool operator < (const Node &rhs) const {
        return d[now] < rhs.d[now];
      }
    } S[1300005], *null = S, *root, *root1;
    inline void init() {
      null->Min[0] = null->Min[1] = 1e7, null->Max[0] = null->Max[1] = -1e7;
      null->ls = null->rs = null;
      root1 = root = null;
    }
    inline Node *build(int l, int r) {
      if (l > r) return null;
      nth_element(S+l, S+mid, S+r+1);
      Node *cur = &S[mid];
      now ^= 1;
      cur->ls = build(l, mid-1), cur->rs = build(mid+1, r);
      return cur->pushup(), cur; 
    }
    inline void insert(Node *&cur, int *d, bool now) {
      if (cur == null) {
        cur = &(S[++cnt] = Node(mp(d[0],d[1]), null));
        return ;
      }
      insert(d[now] >= cur->d[now] ? cur->rs : cur->ls, d, !now);
      cur->pushup();
    }
     
    inline int dis(Node *cur, const pii &a) {
      return max(0, a.se - cur->Max[1]) + max(0, a.fi - cur->Max[0]) + max(0, cur->Min[0] - a.fi) + max(0, cur->Min[1] - a.se);
    }
    inline void query(Node *cur, const pii &a) {
      chmin(ans, abs(cur->d[0] - a.fi) + abs(cur->d[1] - a.se));
      int disl = dis(cur->ls, a), disr = dis(cur->rs, a);
      if (disl < disr) {
        if (disl < ans) query(cur->ls, a);
        if (disr < ans) query(cur->rs, a);
      }
      else {
        if (disr < ans) query(cur->rs, a);
        if (disl < ans) query(cur->ls, a);
      }
    }
      
      
    int main() {
      init();
      in, cnt, m;
      lop1(i, cnt) {
        in, x, y;
        S[i] = Node(mp(x, y), null);
      }
      root = build(1, cnt);
      while (m--) { 
        in, op, x, y;
        if (op == 1) {
          d[0] = x, d[1] = y;
          insert(root, d, 0);
        }
        else {
          ans = inft;
          query(root, mp(x, y));
          out, ans, '
    ';
        }
      } 
      return 0;
    }
    
  • 相关阅读:
    asp.net 下载EXCEL文件
    C# 泛型实现Table与实体的相互转换
    SQL处理数据并发,解决ID自增
    html Canvas 画图 能够选择并能移动
    AJAX get/post;
    (转) C# Async与Await的使用
    FormattableString 取代特定区域字符串
    少用 string.Format
    少用 string.Format
    如何重写object虚方法
  • 原文地址:https://www.cnblogs.com/storz/p/10264173.html
Copyright © 2020-2023  润新知