ZOJ 1453Surround the Trees(凸包)

Surround the Trees
點我找原題

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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.

ZOJ 1453Surround the Trees(凸包) - NatureRan - NatureRan

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


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


Sample Output

243.06


凸包的算法只看了一遍就嘗試着來寫了,結果雖然ac了,但是代碼寫得太亂,到頭來自己也搞不清自己的代碼了,但是能ac還是很開心的,之前碰到的問題就是有多個點排一直線的話,所用的長度是整條線段的兩倍,但實際上當樹的個數大於2棵時是不會出錯的,因爲棧中所保存的最後一個點就是第一個點,在計算總長度時不會出錯,但是如果只有兩棵樹,就無法將p[n]壓入棧,也許是我的寫法還不夠成熟,還得再不研究一下別人的模板。

#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[n]=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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章