-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCHT.cpp
More file actions
64 lines (47 loc) · 1.72 KB
/
CHT.cpp
File metadata and controls
64 lines (47 loc) · 1.72 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <bits/stdc++.h>
using namespace std;
struct CHT {
struct Line {
int slope, yIntercept;
Line(int slope, int yIntercept) : slope(slope), yIntercept(yIntercept) {}
int val(int x) {
return slope * x + yIntercept;
}
int intersect(Line y) {
return (int)ceil((double)(y.yIntercept - yIntercept) / (slope - y.slope));
}
};
deque<pair<Line, int>> dq;
// each element holds the line (slope/y-intercept), and the intersection with the LAST line
void insert(int slope, int yIntercept) {
Line newLine(slope, yIntercept);
// dq.back().second is the intersection of the last line with the second last line
// dq.back().first is the last line
while (dq.size() > 1 && dq.back().second >= dq.back().first.intersect(newLine))
dq.pop_back();
if (dq.empty()) {
dq.emplace_back(newLine, 0);
return;
}
dq.emplace_back(newLine, dq.back().first.intersect(newLine));
}
int query(int x) {
// find first intersection that is greater than the x-val, the line before this will have the lowest y-val
while (dq.size() > 1) {
if (dq[1].second <= x) dq.pop_front();
else break;
}
return dq[0].first.val(x);
}
int query2(int x) {
auto qry = *lower_bound(dq.rbegin(), dq.rend(),
make_pair(Line(0, 0), x),
[&](const pair<Line, int> &a, const pair<Line, int> &b) {
return a.second > b.second;
});
return qry.first.val(x);
}
};
int main() {
return 0;
}