-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcht.cpp
More file actions
31 lines (31 loc) · 779 Bytes
/
cht.cpp
File metadata and controls
31 lines (31 loc) · 779 Bytes
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
// Convex Hull Trick (max)
// https://youtu.be/TSvXG35mmRE?t=7853
struct CHT {
struct Linear {
ll a, b;
Linear(ll a=0, ll b=0): a(a), b(b) {}
ll operator()(ll x) const { return a*x+b;}
};
deque<Linear> ls;
void add(ll a, ll b) {
Linear l(a,b);
assert(ls.size() == 0 || ls.back().a <= l.a);
while (ls.size() >= 2) {
const Linear& l1 = ls[ls.size()-2];
const Linear& l2 = ls.back();
if ((l.a-l2.a)*(l1.b-l2.b) < (l2.a-l1.a)*(l2.b-l.b)) break;
ls.pop_back();
}
ls.push_back(l);
}
ll operator()(ll x) { // x: asc
ll res = ls[0](x);
while (ls.size() >= 2) {
ll now = ls[1](x);
if (now < res) break;
res = now;
ls.pop_front();
}
return res;
}
};