Description
There are a lot of trees in an area. A peasant wants to buy a rope to surround all these trees. So at first he must know the minimal required length of the rope. However, he does not know how to calculate it. Can you help him?
The diameter and length of the trees are omitted, which means a tree can be seen as a point. The thickness of the rope is also omitted which means a rope can be seen as a line.
There are no more than 100 trees.
Input
The input contains one or more data sets. At first line of each input data set is number of trees in this data set, it is followed by series of coordinates of the trees. Each coordinate is a positive integer pair, and each integer is less than 32767. Each pair is separated by blank.
Zero at line for number of trees terminates the input for your program.
Output
The minimal length of the rope. The precision should be 10^-2.
Analysis
裸的凸包例题,只有一个点的时候输出0.00,只有两个点输出距离*2
Code
#include <stdio.h>
#include <cmath>
using namespace std;
struct pos
{
int x,y;
}t[101]={{1<<30,1<<30}};
int cros(pos a,pos b,pos c)
{
return (a.y-c.y)*(b.x-c.x)-(a.x-c.x)*(b.y-c.y);
}
double dist(pos a,pos b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main()
{
int n;
while (scanf("%d",&n)&&n)
{
for (int i=1;i<=n;i++)
scanf("%d%d",&t[i].x,&t[i].y);
int mark=0;
for (int i=1;i<=n;i++)
if (t[i].x<t[mark].x||t[i].x==t[mark].x&&t[i].y<t[mark].y)
mark=i;
double p,ans=0;
int k=mark;
do
{
int i=0;
double dis=0;
for (int j=1;j<=n;j++)
if (j!=k)
{
if (i)
p=cros(t[k],t[i],t[j]);
if (p<0||!i)
dis=dist(t[k],t[j]),i=j;
}
ans+=dis;
k=i;
}while(mark!=k);
if (n==1)
ans=0;
printf("%.2f\n",ans);
}
return 0;
}
#include <algorithm>
#include <stdio.h>
#include <cmath>
using namespace std;
struct pos
{
int x,y;
bool operator<(pos a)
{
return a.x<x||a.x==x&&a.y<y;
}
}t[101];
int s[101];
double cros(pos a,pos b,pos c)
{
return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}
double dist(pos a,pos b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool cmp(pos a,pos b)
{
return ((cros(a,b,t[0])>0)||(!(cros(a,b,t[0]))&&(dist(a,t[0])<dist(b,t[0]))));
}
int main()
{
int n;
while (scanf("%d",&n)&&n)
{
for (int i=0;i<n;i++)
{
scanf("%d%d",&t[i].x,&t[i].y);
if (t[i]<t[0])
{
pos tmp=t[i];
t[i]=t[0];
t[0]=tmp;
}
}
sort(t+1,t+n,cmp);
int top=3;
s[1]=0;
s[2]=1;
s[3]=2;
for (int i=3;i<n;i++)
{
while (cros(t[i],t[s[top]],t[s[top-1]])>=0)
--top;
s[++top]=i;
}
double ans=dist(t[s[1]],t[s[top]]);
if (n==1)
ans=0;
else
if (n==2)
ans=dist(t[s[1]],t[s[2]])*2;
else
for (int i=1;i<top;i++)
ans+=dist(t[s[i]],t[s[i+1]]);
printf("%.2f\n",ans);
}
return 0;
}