计算几何-二维凸包
定义:在一个二维平面上,能包含所有定点的最小凸多边形叫做凸包。感性来说,把所有定点看成一个个钉子,拿一个橡皮筋套住所有钉子,最后橡皮筋就是凸包。
二维凸包经常用在斜率优化动态规划中,还有一些计算几何的题目。三维凸包不知道有啥用(主要是笔者还不会),就不写进笔记里了。求凸包常见的算法有 Andrew 算法和 Graham 算法,笔者更喜欢前者,这里也着重介绍前者。
前置知识
以下两个算法流程中,都需要判断一个点在有向直线的哪一侧。
这个问题可以转化为已知直线上两点 A,B 和直线的方向(不妨假设 B 在 A 的正方向),此时有另一点 C,判断 C 在直线的哪边。
根据向量叉乘的性质,可以算出
(第一次学感觉挺抽象,右手定则多搞搞就会了)。
Andrew 算法
题目链接
洛谷-P2742(二维凸包模板)
算法流程
这个算法一共分
步骤
步骤
步骤
时间复杂度
步骤
代码实现
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
int n;
struct P{
double x, y;
bool operator < (P that)const{
return (x != that.x) ? (x < that.x) : (y < that.y);
}
}p[N], st[N];int tp;
double cross(P a, P b, P c){
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
}
double dis(P a, P b){
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
double Andrew(){
sort(p + 1, p + 1 + n);
for(int i = 1;i <= n;i++){
while(tp > 1 && cross(st[tp - 1], st[tp], p[i]) <= 0) tp--;
st[++tp] = p[i];
}
int d = tp;//保证下凸包不会被删除
for(int i = n;i;i--){
while(tp > d && cross(st[tp - 1], st[tp], p[i]) <= 0) tp--;
st[++tp] = p[i];
}
double ans = 0;
for(int i = 1;i < tp;i++) ans += dis(st[i], st[i + 1]);
return ans;
}
int main(){
scanf("%d",&n);
for(int i = 1;i <= n;i++) scanf("%lf%lf",&p[i].x,&p[i].y);
printf("%.2lf\n",Andrew());
return 0;
}
一些细节
笔者的代码实现里,排序后的第
Graham算法
此算法和 Andrew 算法类似,都是维护一个凸壳,最终变成一个凸包。
但本算法对点进行极角排序,从最下面的点开始,维护一个凸壳。由此就不用上下凸壳各找一次,而是一步到位直接找到凸包。但是实现的时候容易写错(特别是极角排序),个人感觉不如第一个算法。
洛谷-P3829
凸包的一个小小拓展。
如图所示,不难发现其实所求的答案就等于每个信用卡内接的
首先需要一点数学能力,可以得出,把一个在
此时就是一个简单的凸包问题了,直接求解即可。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
struct P{
double x, y;
bool operator < (P that)const{
return (x != that.x) ? (x < that.x) : (y < that.y);
}
}p[N], st[N];int tp;
P rotate(double x, double y, double the){
return (P){x * cos(the) - y * sin(the), x * sin(the) + y * cos(the)};
}
double cross(P a, P b, P c){
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
}
double dis(P a, P b){
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
int n;
double Andrew(){
sort(p + 1, p + 1 + n);
for(int i = 1;i <= n;i++){
while(tp > 1 && cross(st[tp - 1], st[tp], p[i]) <= 0) tp--;
st[++tp] = p[i];
}
int d = tp;
for(int i = n - 1;i;i--){
while(tp > d && cross(st[tp - 1], st[tp], p[i]) <= 0) tp--;
st[++tp] = p[i];
}
double ans = 0;
for(int i = 1;i < tp;i++) ans += dis(st[i], st[i + 1]);
return ans;
}
double x, y, z, a, b, c, r;
double dx[4] = {-1, -1, 1, 1}, dy[4] = {-1, 1, 1, -1};
int main(){
scanf("%d%lf%lf%lf",&n,&a,&b,&r);
a = a / 2.0 - r, b = b / 2.0 - r;swap(a, b);
int idx = 0;
for(int i = 1;i <= n;i++){
scanf("%lf%lf%lf",&x,&y,&z);
for(int k = 0;k < 4;k++){
P t = rotate(dx[k] * a, dy[k] * b, z);
t.x += x, t.y += y;
p[++idx] = t;
}
}
n <<= 2;
printf("%.2lf\n",Andrew() + 2 * acos(-1.0) * r);
return 0;
}
总结
时至今日,已经不会有裸的凸包题出现在竞赛里了。一般来说凸包尝尝结合动态规划、贪心、图论等知识点考察,而这些题的难点不在求解凸包上。所以凸包只是一个辅助工具(就像盘里的洋葱一样~),把那些题目放在这里不太合适,笔者就不过多介绍了。