Skip to content

Commit 8154253

Browse files
committed
add CHT
1 parent 536f7a7 commit 8154253

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ AtCoder解説放送ライブラリ集
1717
|名前|コード|説明|
1818
|:--|:--|:--|
1919
|BIT|[bit.cpp](bit.cpp)|Binary Indexed Tree (Fenwick Tree)|
20-
|UnionFind|[uf.cpp](uf.cpp)|Union Find|
20+
|UnionFind|[uf.cpp](uf.cpp)|Union Find (DSU)|
21+
|CHT|[cht.cpp](cht.cpp)|Convex Hull Trick|
2122

2223
### 数学
2324
|名前|コード|説明|

cht.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Convex Hull Trick (max)
2+
// https://youtu.be/TSvXG35mmRE?t=7853
3+
struct CHT {
4+
struct Linear {
5+
ll a, b;
6+
Linear(ll a=0, ll b=0): a(a), b(b) {}
7+
ll operator()(ll x) const { return a*x+b;}
8+
};
9+
deque<Linear> ls;
10+
void add(ll a, ll b) {
11+
Linear l(a,b);
12+
assert(ls.size() == 0 || ls.back().a <= l.a);
13+
while (ls.size() >= 2) {
14+
const Linear& l1 = ls[ls.size()-2];
15+
const Linear& l2 = ls.back();
16+
if ((l.a-l2.a)*(l1.b-l2.b) < (l2.a-l1.a)*(l2.b-l.b)) break;
17+
ls.pop_back();
18+
}
19+
ls.push_back(l);
20+
}
21+
ll operator()(ll x) { // x: asc
22+
ll res = ls[0](x);
23+
while (ls.size() >= 2) {
24+
ll now = ls[1](x);
25+
if (now < res) break;
26+
res = now;
27+
ls.pop_front();
28+
}
29+
return res;
30+
}
31+
};

0 commit comments

Comments
 (0)