Surround the Trees

来源:互联网 发布:朱莉德尔佩 知乎 编辑:程序博客网 时间:2024/06/05 00:15

Problem 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.
 

Sample Input
9 12 7 24 9 30 5 41 9 80 7 50 87 22 9 45 1 50 7 0
 

Sample Output
243.06
 

求凸包


#include<iostream>
#include <iomanip>
#include<algorithm>
#include<cmath>
using namespace std;
struct Point{
   int x;
   int y;
}p[1000000];
Point queue[10000];
Point start;
double distance1(Point a,Point b)
{


  return sqrt(pow(b.x-a.x,2)+pow(b.y-a.y,2));


}
double direction(Point a,Point b,Point c)
{
   return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);


}


bool cmp(const Point a,const Point b)
{
    
  int k=(a.x-start.x)*(b.y-start.y)-(b.x-start.x)*(a.y-start.y);
  if(k>0)
  {
     return true;
  
  }
  if(k==0)
  {
     if(distance1(start,a)<distance1(start,b))
return true;
  
  }
  return false;


}
void ConvexB(int n)
{
   queue[0]=p[0];
   queue[1]=p[1];
   queue[2]=p[2];
   int count=3;
   int top=2;
   for(int i=3;i<n;i++)
   {


       while(count>=2)
  {
           Point nexttop=queue[top-1];
      Point front=queue[top];
  int dir=direction(nexttop,front,p[i]);
  if(dir>0)
  {
     break;
  }
  top--;
  count--;


   
   
   
  }
   top++;
count++;
   queue[top]=p[i];
 


   }
   if(top>=2)
   {
 double re=0.0;
      for(int j=0;j<top;j++)
 {
   re+=distance1(queue[j],queue[j+1]);
 
 }
 re+=distance1(queue[top],queue[0]);
     printf("%.2lf\n",re);
   }






}


int main()
{
//freopen("in.txt","r",stdin);



int n;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
int i=1;
int px=-1;
int py=-1;
int p1;
   for(i=0;i<n;i++)
{
  scanf("%d%d",&p[i].x,&p[i].y);
           if(py==-1||p[i].y<py)
  {
  px=p[i].x;
  py=p[i].y;
               p1=i;
     
    
  }
  if(p[i].y==py)
  {
      if(p[i].x<px)
  {
    
  px=p[i].x;
  py=p[i].y;
               p1=i;
    
  }
  
  }


  



}
if(n<=1)
{
cout<<0.00<<endl;
continue;
}
if(n==2)
{
  printf("%.2lf\n",distance1(p[1],p[0]));
  continue;

}
Point temp=p[0];
p[0]=p[p1];
p[p1]=temp;
          
start=p[0];
sort(p+1,p+n,cmp);
ConvexB(n);
     

}
   return 0;


}


原创粉丝点击