XIII.[USACO5.1]圈奶牛Fencing the Cows /【模板】二维凸包

相信大家都知道Graham算法(gift wrapping)。但是这个算法不好推广。这里使用便于推广的Andrew算法。

具体而言,本算法将所有点按照\(x\)为第一关键字,\(y\)为第二关键字排序,然后从前往后扫一遍求出下凸包,再从后往前扫一遍求出上凸包,两个拼一起就得到了完整的凸包。

代码:

#include<bits/stdc++.h>
using namespace std;
int n,s1[100100],t1,s2[100100],t2;
struct Vector{
	double x,y;
	Vector(double X=0,double Y=0){x=X,y=Y;}
	friend Vector operator +(const Vector &u,const Vector &v){return Vector(u.x+v.x,u.y+v.y);}
	friend Vector operator -(const Vector &u,const Vector &v){return Vector(u.x-v.x,u.y-v.y);}
	friend Vector operator *(const Vector &u,const double &v){return Vector(u.x*v,u.y*v);}
	friend Vector operator /(const Vector &u,const double &v){return Vector(u.x/v,u.y/v);}
	friend double operator &(const Vector &u,const Vector &v){return u.x*v.y-u.y*v.x;}//cross times
	friend double operator |(const Vector &u,const Vector &v){return u.x*v.x+u.y*v.y;}//point times
	friend bool operator <(const Vector &u,const Vector &v){return u.x==v.x?u.y<v.y:u.x<v.x;}
	double operator ~()const{return sqrt(x*x+y*y);}
	void read(){scanf("%lf%lf",&x,&y);}
	void print(){printf("(%lf,%lf)\n",x,y);}
}p[100100];
double res;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)p[i].read();
	sort(p+1,p+n+1);
	for(int i=1;i<=n;i++){
		while(t1>=2&&((p[i]-p[s1[t1]])&(p[s1[t1]]-p[s1[t1-1]]))>=0)t1--;
		s1[++t1]=i;
	}
	for(int i=n;i>=1;i--){
		while(t2>=2&&((p[i]-p[s2[t2]])&(p[s2[t2]]-p[s2[t2-1]]))>=0)t2--;
		s2[++t2]=i;
	}
	for(int i=1;i<t1;i++)res+=~(p[s1[i+1]]-p[s1[i]]);
	for(int i=1;i<t2;i++)res+=~(p[s2[i+1]]-p[s2[i]]);
	printf("%.2lf\n",res);
	return 0;
}