1. 程式人生 > >P2742 [USACO5.1]圈奶牛Fencing the Cows

P2742 [USACO5.1]圈奶牛Fencing the Cows

space open += define ini 計算 保留 惡心 com

題目描述

農夫約翰想要建造一個圍欄用來圍住他的奶牛,可是他資金匱乏。他建造的圍欄必須包括他的奶牛喜歡吃草的所有地點。對於給出的這些地點的坐標,計算最短的能夠圍住這些點的圍欄的長度。

輸入輸出格式

輸入格式:

輸入數據的第一行包括一個整數 N。N(0 <= N <= 10,000)表示農夫約翰想要圍住的放牧點的數目。接下來 N 行,每行由兩個實數組成,Xi 和 Yi,對應平面上的放牧點坐標(-1,000,000 <= Xi,Yi <= 1,000,000)。數字用小數表示。

輸出格式:

輸出必須包括一個實數,表示必須的圍欄的長度。答案保留兩位小數。

輸入輸出樣例

輸入樣例#1:
4
4 8
4 12
5 9.3
7 8
輸出樣例#1:
12.00

說明

題目翻譯來自NOCOW。

USACO Training Section 5.1

計算幾何,確實讓人惡心。。。

技術分享

這題就是一個裸的凸包,

用A什麽算法求,

註意一下,

需要開double的不要忘了開double!!!!!!!!!!

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5
#include<algorithm> 6 #define vec point 7 using namespace std; 8 const double eps=1e-8; 9 const int MAXN=10001; 10 int n; 11 void read(int &n) 12 { 13 char c=+;int x=0;bool flag=0; 14 while(c<0||c>9){c=getchar();if(c==-)flag=1;} 15 while(c>=0&&c<=
9){x=x*10+(c-48);c=getchar();} 16 flag==1?n=-x:n=x; 17 } 18 inline int dcmp(double x) 19 { 20 if(fabs(x)<eps) return 0; 21 else return x>0?1:-1; 22 } 23 struct point 24 { 25 double x,y; 26 inline point(double x=0,double y=0):x(x),y(y){}; 27 }p[MAXN],ch[MAXN]; 28 vec operator - (vec a,vec b) {return vec(a.x-b.x,a.y-b.y);} 29 vec operator + (vec a,vec b) {return vec(a.x+b.x,a.y+b.y);} 30 vec operator == (vec a,vec b){return (dcmp(a.x-b.x)==0&&dcmp(a.y-b.y)==0);} 31 int comp(const point &a,const point &b) 32 { 33 if(a.x==b.x) return a.y<b.y; 34 else return a.x<b.x; 35 } 36 int stack[MAXN]; 37 double cross(vec a,vec b){return a.x*b.y-a.y*b.x;} 38 int convex_hull() 39 { 40 sort(p+1,p+n+1,comp); 41 int top=1; 42 for(int i=1;i<=n;i++) 43 { 44 while(top>2&& dcmp(cross(ch[top-1]-ch[top-2], p[i]-ch[top-2]))<=0) top--; 45 ch[top++]=p[i]; 46 } 47 int tmp=top+1; 48 for(int i=n-1;i>=1;i--) 49 { 50 while(top+1>tmp&& dcmp(cross(ch[top-1]-ch[top-2], p[i]-ch[top-2]))<=0) top--; 51 ch[top++]=p[i]; 52 } 53 if(n>2) top--; 54 return top; 55 } 56 double dis(point a,point b) 57 { 58 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 59 } 60 int main() 61 { 62 //freopen("fc.in","r",stdin); 63 //freopen("fc.out","w",stdout); 64 read(n); 65 //ios::sync_with_stdio(0); 66 for(int i=1;i<=n;i++) 67 { 68 double a,b; 69 cin>>a>>b; 70 p[i]=point(a,b); 71 } 72 int num=convex_hull(); 73 double ans=0.0; 74 for(int i=1;i<num;i++) 75 ans+=dis(ch[i],ch[i+1]); 76 ans+=dis(ch[num],ch[1]); 77 printf("%.2lf",ans); 78 return 0; 79 }

P2742 [USACO5.1]圈奶牛Fencing the Cows