Matrix_code

data-structure - Convex Hull - Dynamic

Mar 23rd, 2020 (edited)
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. const ll is_query = -(1LL<<62);
  2. struct Line {
  3.     ll m, b;
  4.     mutable function<const Line*()> succ;
  5.     bool operator<(const Line& rhs) const {
  6.         if (rhs.b != is_query) return m < rhs.m;
  7.         const Line* s = succ();
  8.         if (!s) return 0;
  9.         ll x = rhs.m;
  10.         return b - s->b < (s->m - m) * x;
  11.     }
  12. };
  13. struct HullDynamic : public multiset<Line> { // will maintain upper hull for maximum
  14.     bool bad(iterator y) {
  15.         auto z = next(y);
  16.         if (y == begin()) {
  17.             if (z == end()) return 0;
  18.             return y->m == z->m && y->b <= z->b;
  19.         }
  20.         auto x = prev(y);
  21.         if (z == end()) return y->m == x->m && y->b <= x->b;
  22.         return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m);
  23.     }
  24.     void insert_line(ll m, ll b) {
  25.         auto y = insert({ m, b });
  26.         y->succ = [=] { return next(y) == end() ? 0 : &*next(y); };
  27.         if (bad(y)) { erase(y); return; }
  28.         while (next(y) != end() && bad(next(y))) erase(next(y));
  29.         while (y != begin() && bad(prev(y))) erase(prev(y));
  30.     }
  31.     ll eval(ll x) {
  32.         auto l = *lower_bound((Line) { x, is_query });
  33.         return l.m * x + l.b;
  34.     }
  35. };
Add Comment
Please, Sign In to add comment