-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathConvex Hull Trick.cpp
88 lines (77 loc) · 1.54 KB
/
Convex Hull Trick.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
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
struct cht
{
vector<pii> hull;
vector<int> id;
int cur=0;
cht()
{
hull.clear();
id.clear();
}
// Might need double here
bool useless(const pii left, const pii middle, const pii right)
{
return
1LL*(middle.second-left.second)*(middle.first-right.first)
>=1LL*(right.second-middle.second)*(left.first-middle.first);
}
// Inserting line a*x+b with index idx
// Before inserting one by one, all the lines are sorted by slope
void insert(int idx, int a, int b)
{
if(hull.empty())
{
hull.pb(MP(a, b));
id.pb(idx);
}
else
{
if(hull.back().first==a)
{
if(hull.back().second>=b)
{
return;
}
else
{
hull.pop_back();
id.pop_back();
}
}
while(hull.size()>=2 && useless(hull[hull.size()-2], hull.back(), MP(a, b)))
{
hull.pop_back();
id.pop_back();
}
hull.pb(MP(a,b));
id.pb(idx);
}
}
// returns maximum value and the index of the line
// Pointer approach: the queries are sorted non-decreasing
// Otherwise, we will need binary search
pair<ll,int> query(int x)
{
ll ret=-INF;
int idx=-1;
for(int i=cur ; i < hull.size() ; i++)
{
ll tmp=1LL*hull[i].first*x + hull[i].second;
if(tmp>ret)
{
ret=tmp;
cur=i;
idx=id[i];
}
else
{
break;
}
}
return {ret,idx};
}
};
// Slope decreasing, query minimum - Query point increasing.
// Slope increasing, query maximum - Query point increasing.
// Slope decreasing, query maximum - Query point decreasing.
// Slope increasing, query minimum - Query point decreasing.