凸包: 给你n个散落的点,让你求出最小的凸多边形将所有的点包括起来,或者点在边上。
注意 n=1和n=2的情况
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 1050
#define PI 4*atan(1.0)
#define eps 1e-8
struct Node
{
double x,y;
} p[N],stack[N];
double mulit(Node a,Node b,Node c)//向量ab与向量ac的叉乘
{
return ((b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x));
}
double dist(Node s,Node e)//s点与e点的距离的平方(此处如果直接开根怕影响在传递的时候影响精度)
{
return (s.x-e.x)*(s.x-e.x)+(s.y-e.y)*(s.y-e.y);
}
int cmp(Node a,Node b)//设<p1,p2,...pm>为对其余点按以p0为中心的极角逆时针排序所得的点集(如果有多个点有相同的极角,除了距p0最远的点外全部移除)
{
if(mulit(p[0],a,b)>0)//向量p[0]a在向量p[0]b顺时针方向,返回1
return 1;
if(mulit(p[0],b,a)==0&&(dist(p[0],b)-dist(p[0],a)>eps))//p[0]a与p[0]b共线,而且b点距离更远
return 1;
return 0;
}
int Graham(int n)
{
int top=2;
sort(p+1,p+n,cmp);
stack[0]=p[0];
stack[1]=p[1];
stack[2]=p[2];
for(int i=3;i<n;i++)
{
while(top>=1&&mulit(stack[top-1],p[i],stack[top])>=0)
top--;
stack[++top]=p[i];
}
return top;
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
{
for(int i=0; i<n; i++)
scanf("%lf %lf",&p[i].x,&p[i].y);
if(n==1)
{
printf("0.00\n");
continue;
}
else if(n==2){
printf("%.2lf\n",dist(p[0],p[1]));
continue;
}
int k=0;
for(int i=0; i<n; i++)
{
if(p[k].y>p[i].y||(p[k].y==p[i].y&&p[k].x>p[i].x))
k=i;
}
swap(p[0],p[k]);
int top=Graham(n);
double sum=0.0;
for(int i=1; i<=top; i++)
sum+=sqrt(dist(stack[i],stack[i-1]));
sum+=sqrt(dist(stack[0],stack[top]));
printf("%.2lf\n",sum);
}
return 0;
}