题解:P2742 【模板】二维凸包 / [USACO5.1] 圈奶牛Fencing the Cows
前置知识:向量,正弦、余弦函数,跨立实验,极角排序。
凸包是什么?
凸包的意思就是凸多边形。
一大堆点的凸包是什么?
指的是面积最小的、能够围住所有点的多边形。
有点不太直观?想象如下一个东西:有一个无限大的木板(二维平面),这个木板上有一些钉子(散点),你有一个橡皮筋,现在你需要把这个橡皮筋套到这些钉子上,使得它围住所有的钉子。这个橡皮筋就是所谓的凸包。
凸包基本有两个算法:Andrew 和 Graham。这里只对 Graham 做解释(因为笔者认为 Andrew 算两遍很麻烦)。
我们考虑找出
我们将其他的
我们考虑依次处理这
若第
检验在左边还是在右边的过程直接使用跨立实验就好了。
为什么我们这样做是对的?
我们一开始就已经极角排序了,所以我们要找的凸包上的第
模拟检验的过程使用栈即可。
code:
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 1e5+1;
int n,top = 0,sta[N];
struct point{
long double x,y,ang;
}a[N];
inline long double prod(const point &x,const point &y){
return x.x*y.y-x.y*y.x;
}
inline long double dist(const point &x,const point &y){
return sqrtl((x.x-y.x)*(x.x-y.x)+(x.y-y.y)*(x.y-y.y));
}
inline bool cmp(const point &x,const point &y){
if(x.ang!=y.ang){
return x.ang<y.ang;
}
return dist(a[1],x)<dist(a[1],y);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 1;i<=n;++i){
cin >> a[i].x >> a[i].y;
}
for(int i = 2;i<=n;++i){
if(a[i].x<a[1].x||(a[i].x == a[1].x&&a[i].y<a[1].y)){
swap(a[1],a[i]);
}
}
for(int i = 2;i<=n;++i){
a[i].ang = atan2(a[i].y-a[1].y,a[i].x-a[1].x);
}
stable_sort(a+2,a+n+1,cmp);
sta[1] = 1,sta[2] = 2;
top = 2;
for(int i = 3;i<=n;++i){
while(top>=2&&prod({a[sta[top]].x-a[sta[top-1]].x,a[sta[top]].y-a[sta[top-1]].y},{a[i].x-a[sta[top]].x,a[i].y-a[sta[top]].y})<=0){
--top;
}
sta[++top] = i;
}
int lst = 1;
long double ans = 0;
for(int i = top;i>=1;--i){
ans+=dist(a[sta[i]],a[lst]);
lst = sta[i];
}
cout << fixed << setprecision(2) << ans;
return 0;
}