您的位置:首页 > 其它

Surround the Trees(凸包)

2017-08-19 14:31 253 查看
描述:

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.

输入:

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.

输出:

The minimal length of the rope. The precision should be 10^-2.

样例输入:

2

1 1

2 2

9

12 7

24 9

30 5

41 9

80 7

50 87

22 9

45 1

50 7

0

样例输出:

2.83

243.06

 

题目大意:

给你n颗树的坐标,问你最短需要多少长的绳子能把这n颗树围起来。

极角序Graham扫描法(基本思路):

1.找出最左下角的点(先最下再最左)记为p[0]。

2.以p[0]为原点,对p[1],p[2]......p[n-1]按极角大小从大到小排序。

3.把p[0],p[1],p[2]压入栈

for(i=3;i<n;i++)

{

while(1)

{

判断栈顶元素k1,栈顶下一个元素k2与p[i]的关系

如果k2k1左拐得到p[i]或处于一直线

弹出k1

else

break;

}

p[i]入栈

}
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<stack>
using namespace std;
struct point
{
int x;
int y;
}p[1005];
stack<point>asd;
double Distance(point A,point B)
{
return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
}
bool cmp1(point p1, point p2)
{
if(p1.y==p2.y)
return p1.x<p2.x;
return p1.y<p2.y;
}
bool cmp2(point p1, point p2)
{
if(atan2(p1.y-p[0].y,p1.x-p[0].x)==atan2(p2.y-p[0].y,p2.x-p[0].x))			//如果极角相同选择与p【0】更近的那棵树
return Distance(p1,p[0])<Distance(p2,p[0]);
return atan2(p1.y-p[0].y,p1.x-p[0].x)>atan2(p2.y-p[0].y,p2.x-p[0].x);
}
int check(point p1,point p2,point p3)											//检验拐点是否向右拐
{
if((p3.x-p1.x)*(p2.y-p1.y)-(p2.x-p1.x)*(p3.y-p1.y)<=0)
return 0;
return 1;
}
int main()
{
int n;
while(scanf("%d",&n),n)
{
for(int i=0;i<n;i++)
{
scanf("%d %d",&p[i].x,&p[i].y);
}
if(n==1)											//分三种情况讨论1.一棵树就是0,两棵树就是2倍的树的距离
printf("0.00\n");
else if(n==2)
{
printf("%.2f\n",Distance(p[0],p[1])*2) ;
}
else
{
sort(p,p+n,cmp1);								//选出y坐标最小,如果y坐标相同选最左边的树
sort(p+1,p+n,cmp2);								//把剩下n-1颗树与p【0】坐标对应按极角大小从大到小排序
asd.push(p[0]);									//把p[0],p[1],p[2]压入栈
asd.push(p[1]);
asd.push(p[2]);
for(int i=3;i<n;i++)
{
while(true)
{
point k2=asd.top();
asd.pop();
point k3=asd.top();
asd.push(k2);
if(check(k3,k2,p[i])==0)
asd.pop();
else
break;
}
asd.push(p[i]);
}																	//结束后asd数组储存的就是凸包的各个点
point k=asd.top(),k4,k5;
double len=0;
while(!asd.empty())
{
k4=asd.top();
asd.pop();
if(!asd.empty())
k5=asd.top();
else
k5=k;
len+=Distance(k4,k5);											// 计算最后的长度
}
printf("%.2f\n",len);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: