您的位置:首页 > 其它

ZOJ 1453Surround the Trees(凸包)

2018-01-22 09:11 477 查看
Surround the Trees点我找原题Time Limit: 2 Seconds      Memory Limit: 65536 KBThere 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.
InputThe 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.
OutputThe minimal length of the rope. The precision should be 10^-2.
Sample Input
12 7 
24 9 
30 5 
41 9 
80 7 
50 87 
22 9 
45 1 
50 7 
0
Sample Output243.06
凸包的算法只看了一遍就尝试着来写了,结果虽然ac了,但是代码写得太乱,到头来自己也搞不清自己的代码了,但是能ac还是很开心的,之前碰到的问题就是有多个点排一直线的话,所用的长度是整条线段的两倍,但实际上当树的个数大于2棵时是不会出错的,因为栈中所保存的最后一个点就是第一个点,在计算总长度时不会出错,但是如果只有两棵树,就无法将p
压入栈,也许是我的写法还不够成熟,还得再不研究一下别人的模板。#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
double pi=2*asin(1);
struct point
{
int x,y;
double angle;
}p[105];
stack <point> s;
int cmp1(point a,point b)
{
if(a.y==b.y) return a.x<b.x;
else return a.y<b.y;
}
double cmp2(point a,point b)
{
if(a.angle==b.angle)
{
if(a.y==b.y) return a.x>b.x;
else return a.y>b.y;
}
return a.angle<b.angle;
}
int cross(point a,point b,point c)
{
return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
double LL(point a,point b)
{
return sqrt(1.0*(a.x-b.x)*(a.x-b.x)+1.0*(a.y-b.y)*(a.y-b.y));
}
int main(int argc, char *argv[])
{
int n,i,j;
point p0,p1;
while(cin>>n&&n)
{
for(i=0;i<n;i++)
{
cin>>p[i].x>>p[i].y;
}
sort(p,p+n,cmp1);
for(i=1;i<n;i++)
{
if(p[i].x==p[0].x) p[i].angle=pi/2;
else if(p[i].x>p[0].x) p[i].angle=atan(1.0*(p[i].y-p[0].y)/(p[i].x-p[0].x));
else if(p[i].x<p[0].x) p[i].angle=pi+atan(1.0*(p[i].y-p[0].y)/(p[i].x-p[0].x));
}
sort(p+1,p+n,cmp2);
/*for(i=0;i<n;i++)
{
cout<<p[i].x<<" "<<p[i].y<<endl;
} */
p
=p[0];
p0=p[1];p1=p[2];
int ii=2;
s.push(p[0]);s.push(p[1]);s.push(p[2]);
for(i=3;i<=n;i++)
{
if(ii==n) break;
if(cross(p0,p1,p[i])<=0)
{
ii=i;
s.pop();
s.push(p[i]);
p1=p[i];
}
if(i==n)
{
p0=p1;p1=p[ii];i=ii;s.push(p[ii+1]);
}
}
s.pop();
double len=0;
/*cout<<endl;
while(!s.empty())
{
point p=s.top();s.pop();
cout<<p.x<<" "<<p.y<<endl;
}*/
while(!s.empty())
{
p0=s.top();s.pop();
if(s.empty()) break;
p1=s.top();
len+=LL(p0,p1);
}
if(n==2) len*=2;
printf("%.2f\n",len);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: