1401. 围住奶牛
题目链接
1401. 围住奶牛
农夫约翰想要建造一个围栏来围住奶牛。
构建这个围栏时,必须将若干个奶牛们喜爱的地点都包含在围栏内。
现在给定这些地点的具体坐标,请你求出将这些地点都包含在内的围栏的最短长度是多少。
注意:围栏边上的点也算处于围栏内部。
输入格式
第一行包含整数 \(N\),表示奶牛们喜爱的地点数目。
接下来 \(N\) 行,每行包含两个实数 \(X_i,Y_i\),表示一个地点的具体坐标。
输出格式
输出一个实数,表示围栏最短长度。
保留两位小数。
数据范围
\(0 \le N \le 10000\),
\(-10^6 \le X_i,Y_i \le 10^6\),
数据保证所有奶牛不会全部处在同一条直线上。
输入样例:
4
4 8
4 12
5 9.3
7 8
输出样例:
12.00
解题思路
凸包,andrew
算法先求下/上凸壳,然后求上/下凸壳。流程:将所有点的横坐标按第一关键字,纵坐标按第二关键字排序,用栈维护凸壳点的信息,以求解下凸壳为例,对于栈中最后两点形成的直线,如果当前点在该直线下方(用叉积判断),则栈中最后一个点显然不会成为下凸壳的端点,弹出即可,最后逆着来求解上凸壳
- 时间复杂度:\(O(nlogn)\)
代码
// Problem: 围住奶牛
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1403/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// %%%Skyqwq
#include <bits/stdc++.h>
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
template <typename T> void inline read(T &x) {
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
const int N=1e4+5;
const double eps=1e-8;
typedef pair<double,double> PDD;
int n,stk[N],top;
PDD a[N];
double res;
int sign(double x)
{
if(fabs(x)<eps)return 0;
if(x>0)return 1;
return -1;
}
double cross(double x1,double y1,double x2,double y2)
{
return x1*y2-x2*y1;
}
double area(PDD a,PDD b,PDD c)
{
return cross(b.fi-a.fi,b.se-a.se,c.fi-a.fi,c.se-a.se);
}
double get_dist(PDD a,PDD b)
{
return sqrt((a.fi-b.fi)*(a.fi-b.fi)+(b.se-a.se)*(b.se-a.se));
}
void andrew()
{
sort(a+1,a+1+n);
for(int i=1;i<=n;i++)
{
while(top>=2&&sign(area(a[stk[top-1]],a[stk[top]],a[i]))<=0)top--;
stk[++top]=i;
}
int k=top;
for(int i=n;i>=1;i--)
{
while(top>k&&sign(area(a[stk[top-1]],a[stk[top]],a[i]))<=0)top--;
stk[++top]=i;
}
if(n>1)top--;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%lf%lf",&a[i].fi,&a[i].se);
andrew();
for(int i=1;i<top;i++)res+=get_dist(a[stk[i]],a[stk[i+1]]);
res+=get_dist(a[stk[1]],a[stk[top]]);
printf("%.2lf",res);
return 0;
}