Dang_Quan_10_Tin

Dynamic ConvexHull Trick

Mar 3rd, 2021
1,334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. struct Line
  2. {
  3.     mutable ll k, m, p;
  4.     bool operator<(const Line& o) const
  5.     {
  6.         if (k==o.k) return m>o.m;
  7.         return k > o.k;
  8.     }
  9.     bool operator<(ll x) const
  10.     {
  11.         return p < x;
  12.     }
  13. };
  14.  
  15.  
  16. struct LineContainer : multiset<Line, less<>>
  17. {
  18.     static const ll inf = LLONG_MAX;
  19.     ll div(ll a, ll b)
  20.     {
  21.         return a / b - ((a ^ b) < 0 && a % b);
  22.     }
  23.     bool isect(iterator x, iterator y)
  24.     {
  25.         if (y == end())
  26.             return x->p = inf, 0;
  27.         if (x->k == y->k)
  28.             x->p = x->m < y->m ? inf : -inf;
  29.         else
  30.             x->p = div(y->m - x->m, x->k - y->k);
  31.         return x->p >= y->p;
  32.     }
  33.     void add(ll k, ll m)
  34.     {
  35.         auto z = insert({k, m, 0}), y = z++, x = y;
  36.         while (isect(y, z))
  37.             z = erase(z);
  38.         if (x != begin() && isect(--x, y))
  39.             isect(x, y = erase(y));
  40.         while ((y = x) != begin() && (--x)->p >= y->p)
  41.             isect(x, erase(y));
  42.     }
  43.     ll query(ll x)
  44.     {
  45.         assert(!empty());
  46.         auto l = *lower_bound(x);
  47.         return l.k * x + l.m;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment