凸包模板(以洛谷P2742为例)
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define maxn 100005 using namespace std; double X,Y; struct node { double x,y; }e[maxn],stk[maxn]; bool cmp(node a,node b) { if (a.y==b.y) return a.x<b.x; return a.y<b.y; } bool cmp2(node a,node b)//极角排序 { if (atan2(a.y-Y,a.x-X)==atan2(b.y-Y,b.x-X)) return a.x<b.x; return (atan2(a.y-Y,a.x-X))<(atan2(b.y-Y,b.x-X)); } double cross(node a,node b,node c) { node ab,ac; ab.x=b.x-a.x; ab.y=b.y-a.y; ac.x=c.x-a.x; ac.y=c.y-a.y; return ab.x*ac.y-ab.y*ac.x; } double getdis(node a,node b) { node ab; ab.x=b.x-a.x; ab.y=b.y-a.y; return sqrt(ab.x*ab.x+ab.y*ab.y); } int main() { int i,n,top; double ans; scanf("%d",&n); for (i=0;i<n;i++) scanf("%lf%lf",&e[i].x,&e[i].y); if (n<3) { if (n==1) printf("0\n"); else if (n==2) printf("%.2lf\n",getdis(e[0],e[1])); return 0; } sort(e,e+n,cmp); top=-1; stk[++top]=e[0]; X=e[0].x;Y=e[0].y; sort(e+1,e+n,cmp2); stk[++top]=e[1]; for (i=2;i<n;i++) { while (cross(stk[top-1],stk[top],e[i])<0) top--; stk[++top]=e[i]; } ans=0; for (i=1;i<=top;i++) { ans+=getdis(stk[i],stk[i-1]); } ans+=getdis(stk[0],stk[top]); printf("%.2lf\n",ans); return 0; }凸包模板