1670: [Usaco2006 Oct]Building the Moat護城河的挖掘
Time Limit:?3 Sec??Memory Limit:?64 MBSubmit:?387??Solved:?288
[Submit][Status][Discuss]
Description
為了防止口渴的食蟻獸進入他的農場,Farmer John決定在他的農場周圍挖一條護城河。
農場里一共同擁有N(8<=N<=5,000)股泉水,而且,護城河總是筆直地連接在河道上的相鄰的兩股泉水。護城河必須能保護全部的泉水,也就是說,能包圍全部的泉水。泉水一定在護城河的內部,或者恰好在河道上。當然。護城河構成一個封閉的環。
挖護城河是一項昂貴的project,于是,節約的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。
Input
* 第1行: 一個整數,N * 第2..N+1行: 每行包括2個用空格隔開的整數。x[i]和y[i],即第i股泉水的位 置坐標?
Output
* 第1行: 輸出一個數字。表示滿足條件的護城河的最短長度。保留兩位小數?
Sample Input
2 10
3 7
22 15
12 11
20 3
28 9
1 12
9 3
14 14
25 6
8 1
25 1
28 4
24 12
4 15
13 5
26 5
21 11
24 4
1 8
Sample Output
HINT
Source
凸包 卡殼
凸包模板題
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
#define maxn 5005
using namespace std;
int n,top;
double ans;
struct P{int x,y;}p[maxn],s[maxn];
inline int read()
{int x=0,f=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;
}
inline P operator-(const P &a,const P &b)
{return (P){a.x-b.x,a.y-b.y};
}
inline ll operator*(const P &a,const P &b)
{return a.x*b.y-a.y*b.x;
}
inline ll dis(P a,P b)
{return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
inline bool operator<(const P &a,const P &b)
{ll t=(a-p[1])*(b-p[1]);if (t==0) return dis(p[1],a)<dis(p[1],b);else return t<0;
}
inline void solve()
{int t=1;F(i,2,n) 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];F(i,3,n){while (top>=2&&(s[top]-s[top-1])*(p[i]-s[top-1])>=0) top--;s[++top]=p[i];}s[top+1]=p[1];F(i,1,top) ans+=sqrt(dis(s[i],s[i+1]));
}
int main()
{n=read();F(i,1,n) p[i].x=read(),p[i].y=read();solve();printf("%.2lf\n",ans);return 0;
}