-
Notifications
You must be signed in to change notification settings - Fork 0
/
convex_hull_trick_Line_container.cpp
36 lines (34 loc) · 1.35 KB
/
convex_hull_trick_Line_container.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Description: Container where you can add lines of the form kx+m, and query maximum values at points x.
// Useful for dynamic programming (``convex hull trick'').
// Time: O(\log N)
// For minimum value just multiply -1 with k , m and query ;
// ex : if you want to add x,y then add -x,-y if query is z then answer will be -z
struct Line {
mutable ll k, m, p;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(ll x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
const ll INF = LLONG_MAX;
ll div(ll a, ll b) { // floored division
return a / b - ((a ^ b) < 0 && a % b); }
bool isect(iterator x, iterator y) {
if (y == end()) { x->p = INF; return false; }
if (x->k == y->k) x->p = x->m > y->m ? INF : -INF;
else x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(ll k, ll m) {
auto z = insert({k, m, 0}), y = z++, x = y;
while (isect(y, z)) z = erase(z);
if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
ll query(ll x) {
assert(!empty());
auto l = *lower_bound(x);
return l.k * x + l.m;
}
};