Advertisement
slash0t

li chao tree

Aug 3rd, 2024 (edited)
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. struct line {
  2.     int k = 0, m = inf;
  3.     line() {}
  4.     line(int k, int m) : k(k), m(m) {}
  5.     int get(int x) {
  6.         return k * x + m;
  7.     }
  8. };
  9.  
  10. struct li_chao_tree {
  11.     struct node
  12.     {
  13.         line lin;
  14.         node* l = nullptr;
  15.         node* r = nullptr;
  16.     };
  17.  
  18.     int n;
  19.     node* root = nullptr;
  20.  
  21.     li_chao_tree(int _n = 1) : n(_n) {
  22.         root = new node();
  23.     }
  24.  
  25.     node* upd(node* n, int tl, int tr, line L) {
  26.         if (!n) {
  27.             n = new node();
  28.         }
  29.         if (tl > tr) {
  30.             return n;
  31.         }
  32.         int tm = (tl + tr) / 2;
  33.         bool l = L.get(tl) < n->lin.get(tl);
  34.         bool mid = L.get(tm) < n->lin.get(tm);
  35.         bool r = L.get(tr) < n->lin.get(tr);
  36.         if (!mid && !l && !r) {
  37.             return n;
  38.         }
  39.         if (mid) {
  40.             swap(L, n->lin);
  41.             l = L.get(tl) < n->lin.get(tl);
  42.             r = L.get(tr) < n->lin.get(tr);
  43.         }
  44.         if (l) {
  45.             n->l = upd(n->l, tl, tm - 1, L);
  46.         }
  47.         else {
  48.             n->r = upd(n->r, tm + 1, tr, L);
  49.         }
  50.         return n;
  51.     }
  52.  
  53.     node* upd(line l) {
  54.         return upd(root, 0, n, l);
  55.     }
  56.  
  57.     int get(node* n, int tl, int tr, int x) {
  58.         if (!n || tl > tr) {
  59.             return inf;
  60.         }
  61.         int tm = (tl + tr) / 2;
  62.         if (x == tm) {
  63.             return n->lin.get(x);
  64.         }
  65.         if (x < tm) {
  66.             return min(n->lin.get(x), get(n->l, tl, tm - 1, x));
  67.         }
  68.         else {
  69.             return min(n->lin.get(x), get(n->r, tm + 1, tr, x));
  70.         }
  71.     }
  72.  
  73.     int get(int x) {
  74.         return get(root, 0, n, x);
  75.     }
  76. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement