凸包学习笔记
hzy1
·
·
个人记录
1. 静态二维凸包(Andrew算法)
推荐这篇博客
1.1 算法流程
这个算法单次可以求上凸包或下凸包,求完整凸包上下拼起来即可。
以求上凸包为例,算法流程如下:
(1)先将所有点按照先 x 后 y 升序排序。然后将第 1、2 个点依次入栈。
(2)对于第 i~(i\ge 3) 个点开始,不断执行:如果两点 stk[top-1]~,~i 的斜率优于 stk[top-1]~,~stk[top] 的斜率,就弹出 stk[top]。然后将第 i 个点入栈。
关于判断斜率更优:如图,维护上凸壳时,红线比蓝线更优。当然也可以用叉积判断。
所以如果黑点代表之前栈中的点,那么图中 stk[top] 就要出栈(因为已经按照 x 排序,图中最右边的一定是栈顶)。
1.2 模板:洛谷P2742【模板】二维凸包
代码戳我!
2 动态凸包(\text{std::map} 维护)
分别用两个 \text{std::map}:top 与 down 来维护上下凸包。需要支持:
其中 top[x]/down[x] 表示的是凸包上横坐标为 x 的点的纵坐标,即 top[x]/down[x]=y。
2.1 基本函数
```cpp
pii vec(pii x, pii y) {
return {y.first - x.first, y.second - x.second};
}
int cross(pii a, pii b) {
return a.first * b.second - a.second * b.first;
}
```
### 2.2 判断点是否在凸包内部
如图,以上凸包为例,蓝点在凸包内部,红点在外部。

所以判断是否在内部与静态凸包基本一样,用叉积或者斜率判断即可。
代码,以上凸包为例:
```cpp
bool inside_top(int x, int y) {
auto it = top.lower_bound(x);
if(it == top.end()) return false;
if(it->first == x) return y <= it->second;
if(it == top.begin()) return false;
auto i = it, j = it;
--j;
return cross(vec({j->first, j->second}, {i->first, i->second}), vec({j->first, j->second}, {x, y})) <= 0;
}
```
### 2.3 凸包上单点删除
这个操作是用来删除凸包上不合法的点的,在单点插入时需要使用。
通过点 $i$ 与它两边的点的斜率关系来判断是否删除。
代码,以上凸包为例:
```cpp
bool delete_top(map<int,int>::iterator i) {
if(i == top.begin()) return false;
auto j = i, k = i;
--j;
++k;
if(k == top.end()) return false;
if(cross(vec({j->first, j->second}, {i->first, i->second}), vec({j->first, j->second}, {k->first, k->second})) >= 0) {
top.erase(i);
return true;
}
return false;
}
```
### 2.4 单点插入
以上凸包为例,插入点 $(x,y)$时:
先令 $top[x]=y$,然后不断删除左右两边不符合条件的点,需要用到上面的单点删除。
代码:
> 关于 $\text{std::next}$ 与 $\text{std::prev}$:给它一个迭代器 $it$,返回 $it$ 的下一个/上一个迭代器。
```cpp
void insert_top(int x, int y) {
if(inside_top(x, y)) return;
top[x] = y;
auto i = top.find(x), j = i;
if(i != top.begin()) {// 向左边删
--j;
auto next_j = next(j);
while(delete_top(j)) {
j = next_j;
--j;
next_j = next(j);
}
++j;
}
// assert(j == i);
if(j != top.end()) { //向右边删
while(++j != top.end()) {
auto prev_j = prev(j);
while(delete_top(j)) {
j = prev_j;
++j;
prev_j = prev(j);
}
}
}
}
```
但是这个写法有点蠢,并且 $\text{std::next}$ 与 $\text{std::prev}$ 常数有点大,比 $it++/it--$ 慢。
所以网上更通用的写法大概是这样:
```cpp
void insert_top(int x, int y) {
if(inside_top(x, y)) return;
top[x] = y;
auto i = top.find(x), j = i;
if(i != top.begin()) {
--j;
while(delete_top(j++)) --j;
//注意上面这一行,最后一次会 j++ 但是不会 --j
}
if(++j != top.end()) {
while(delete_top(j--)) ++j;
//同理
}
}
```
代码短,跑得还快,真香~
自此,我们已经写学习了动态凸包所需的所有操作!
### 2.5 模板:CF70D. Professor's task
[我的提交记录](https://www.luogu.com.cn/record/69354047)