[USACO5.1]圈奶牛Fencing the Cows /【模板】二维凸包
二维凸包板子
#include<iostream>
#include<algorithm>
#include<cmath>
#include<math.h>
using namespace std;
const double eps = 1e-10;
struct Point
{
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
};
typedef Point Vector;
Vector operator + (Vector A,Vector B)
{
return Vector(A.x+B.x,A.y+B.y);
}
Vector operator - (Vector A,Vector B)
{
return Vector(A.x-B.x,A.y-B.y);
}
Vector operator * (Vector A,double p)
{
return Vector(A.x*p,A.y*p);
}
Vector operator / (Vector A,double p)
{
return Vector(A.x/p,A.y/p);
}
bool operator < (const Point& a,const Point& b)
{
return a.x<b.x|| (a.x==b.x&&a.y<b.y);
}
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
if(x<0) return -1;
return 1;
}
bool operator == (const Point& a,const Point& b)
{
return dcmp(a.x-b.x)==0&&dcmp(a.y-b.y)==0;
}
Point read_point()
{
double x,y;
cin>>x>>y;
return Vector(x,y);
}
double dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double cross(Vector A,Vector B)
{
return A.x*B.y-B.x*A.y;
}
double length(Vector A)
{
return sqrt(dot(A,A));
}
double convexhull(Point* p,int n,Point* ch)
{
double res=0;
int m=0;
sort(p,p+n);
for(int i=0;i<n;i++)
{
while(m>1&&cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0) m--;
ch[m++]=p[i];
}
int k=m;
for(int i=n-2;i>=0;i--)
{
while(m>k&&cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0) m--;
ch[m++]=p[i];
}
if(n>1) m--;
for(int i=1;i<=m;i++)
{
res+=length(ch[i]-ch[i-1]);
}
return res;
}
int main()
{
int n;
cin>>n;
Point p[10010],ch[10010];
for(int i=0;i<n;i++)
{
p[i]=read_point();
}
double res=convexhull(p,n,ch);
printf("%.2lf",res);
return 0;
}