-
Notifications
You must be signed in to change notification settings - Fork 0
/
LiChaoTree.cpp
121 lines (109 loc) · 2.62 KB
/
LiChaoTree.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using namespace std;
typedef long long ll;
typedef pair<ll, ll> Line;
struct LiChaoTree { // Minimum
ll f(Line l, ll x) {
return l.first * x + l.second;
}
struct Node {
int lnode, rnode;
ll xl, xr;
Line l;
};
vector<Node> nodes;
void init(ll xmin, ll xmax) {
nodes.push_back({ -1,-1,xmin,xmax,{0,1e18} });
}
void insert(int n, Line newline) {
ll xl = nodes[n].xl, xr = nodes[n].xr;
ll xm = (xl + xr) >> 1;
Line llow = nodes[n].l, lhigh = newline;
if (f(llow, xl) >= f(lhigh, xl)) swap(llow, lhigh);
if (f(llow, xr) <= f(lhigh, xr)) {
nodes[n].l = llow;
return;
}
else if (f(llow, xm) <= f(lhigh, xm)) {
nodes[n].l = llow;
if (nodes[n].rnode == -1) {
nodes[n].rnode = nodes.size();
nodes.push_back({ -1,-1,xm + 1,xr,{0,1e18} });
}
insert(nodes[n].rnode, lhigh);
}
else {
nodes[n].l = lhigh;
if (nodes[n].lnode == -1) {
nodes[n].lnode = nodes.size();
nodes.push_back({ -1,-1,xl,xm,{0,1e18} });
}
insert(nodes[n].lnode, llow);
}
}
void insert(Line newLine) {
insert(0, newLine);
}
ll get(int n, ll xq) {
if (n == -1) return 1e18;
ll xl = nodes[n].xl, xr = nodes[n].xr;
ll xm = (xl + xr) >> 1;
if (xq <= xm) return min(f(nodes[n].l, xq), get(nodes[n].lnode, xq));
else return min(f(nodes[n].l, xq), get(nodes[n].rnode, xq));
}
ll get(ll xq) {
return get(0, xq);
}
};
struct LiChaoTree { // Maximum
ll f(Line l, ll x) {
return l.first * x + l.second;
}
struct Node {
int lnode, rnode;
ll xl, xr;
Line l;
};
vector<Node> nodes;
void init(ll xmin, ll xmax) {
nodes.push_back({ -1,-1,xmin,xmax,{0,-1e18} });
}
void insert(int n, Line newline) {
ll xl = nodes[n].xl, xr = nodes[n].xr;
ll xm = (xl + xr) >> 1;
Line llow = nodes[n].l, lhigh = newline;
if (f(llow, xl) >= f(lhigh, xl)) swap(llow, lhigh);
if (f(llow, xr) <= f(lhigh, xr)) {
nodes[n].l = lhigh;
return;
}
else if (f(llow, xm) <= f(lhigh, xm)) {
nodes[n].l = lhigh;
if (nodes[n].rnode == -1) {
nodes[n].rnode = nodes.size();
nodes.push_back({ -1,-1,xm + 1,xr,{0,-1e18} });
}
insert(nodes[n].rnode, llow);
}
else {
nodes[n].l = llow;
if (nodes[n].lnode == -1) {
nodes[n].lnode = nodes.size();
nodes.push_back({ -1,-1,xl,xm,{0,-1e18} });
}
insert(nodes[n].lnode, lhigh);
}
}
void insert(Line newLine) {
insert(0, newLine);
}
ll get(int n, ll xq) {
if (n == -1) return -1e18;
ll xl = nodes[n].xl, xr = nodes[n].xr;
ll xm = (xl + xr) >> 1;
if (xq <= xm) return max(f(nodes[n].l, xq), get(nodes[n].lnode, xq));
else return max(f(nodes[n].l, xq), get(nodes[n].rnode, xq));
}
ll get(ll xq) {
return get(0, xq);
}
};