Description
为了防止口渴的食蚁兽进入他的农场,Farmer John决定在他的农场周围挖一条护城河。农场里一共有N(8<=N<=5,000)股泉水,并且,护城河总是笔直地连接在河道上的相邻的两股泉水。护城河必须能保护所有的泉水,也就是说,能包围所有的泉水。泉水一定在护城河的内部,或者恰好在河道上。当然,护城河构成一个封闭的环。 挖护城河是一项昂贵的工程,于是,节约的FJ希望护城河的总长度尽量小。请你写个程序计算一下,在满足需求的条件下,护城河的总长最小是多少。 所有泉水的坐标都在范围为(1..10,000,000,1..10,000,000)的整点上,一股泉水对应着一个唯一确定的坐标。并且,任意三股泉水都不在一条直线上。以下是一幅包含20股泉水的地图,泉水用”*”表示.图中的直线,为护城河的最优挖掘方案,即能围住所有泉水的最短路线。 路线从左上角起,经过泉水的坐标依次是:(18,0),(6,-6),(0,-5),(-3,-3),(-17,0),(-7,7),(0,4),(3,3)。绕行一周的路径总长为70.8700576850888(…)。答案只需要保留两位小数,于是输出是70.87。
【题目分析】
凸包模板题,感觉operator用起来真方便
【代码】
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
struct P{
int x,y;
}p[5001];
P s[5001];
int top=0;
double ans=0;
inline long long dis(P a,P b)
{return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}
inline P operator-(const P &a,const P &b)
{return (P){a.x-b.x,a.y-b.y};}
inline long long operator*(const P &a,const P &b)
{return a.x*b.y-a.y*b.x;}
inline bool operator<(const P &a,const P &b)
{
long long x=(a-p[1])*(b-p[1]);
if (x==0) return dis(p[1],a)<dis(p[1],b);
else return x<0;
}
int main()
{
int n;
scanf("%d",&n);
for (int i=1;i<=n;++i) scanf("%d%d",&p[i].x,&p[i].y);
int t=1;
for (int i=1;i<=n;++i) if (p[i].y<p[t].y||(p[i].y==p[t].y&&p[i].x<p[t].x)) t=i;//扫描一遍,找到起始点
swap(p[1],p[t]);
sort(p+2,p+n+1);
s[++top]=p[1];s[++top]=p[2];
for (int i=3;i<=n;++i)
{
while (top>=2&&(s[top]-s[top-1])*(p[i]-s[top-1])>=0) top--;
s[++top]=p[i];
}
s[top+1]=p[1];
for (int i=1;i<=top;++i) ans+=sqrt(dis(s[i],s[i+1]));
printf("%.2lf\n",ans);
}