標籤:
傳送門
劉汝佳《演算法競賽入門經典》P272例題6封裝木板
題意:有n塊矩形木板,你的任務是用一個面積盡量小的凸多邊形把它們抱起來,並計算出木板占整個封裝面積的百分比。
輸入:t組資料,每組先輸入木板個數n,接下來n行,每行x,y,w,h,j。(x,y)是木板中心的座標,w是寬,h是高,j是順時針旋轉的角度。
木板互不相交。
輸出:對於每組資料,輸出木板總面積占封裝總面積的百分比,保留小數點後1位。
題解:典型的二維凸包問題,理解並調用模板即可。
#include <math.h>#include <stdio.h>#include <algorithm>using namespace std;typedef struct Point{ double x,y; Point(double x=0,double y=0):x(x),y(y){}}Vector;Vector operator + (Vector A,Vector B){ return Vector(A.x+B.x,A.y+B.y);}Vector operator - (Point A,Point B){ return Vector(A.x-B.x,A.y-B.y);}bool operator <(const Point &a,const Point &b){ return a.x<b.x||(a.x==b.x&&a.y<b.y);}double Cross(Vector A,Vector B){ return A.x*B.y-A.y*B.x;}Vector Rotate(Vector A,double rad){ return Vector(A.x*cos(rad)-A.y*sin(rad),A.x*sin(rad)+A.y*cos(rad));}double ConvexPolygonArea(Point *p,int n){ double area=0; for(int i=1;i<n-1;i++) area+=Cross(p[i]-p[0],p[i+1]-p[0]); return area/2;}double torad(double deg){ return deg/180*acos(-1);}int ConvexHull(Point *p,int n,Point* ch) //注意是*ch{ sort(p,p+n); int m=0; for(int i=0;i<n;i++) { while(m>1&&Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0) m--; ch[m++]=p[i]; } int k=m; for(int i=n-2;i>=0;i--) //注意是--不是++ { while(m>k&&Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0) m--; ch[m++]=p[i]; } if(n>1) m--; return m;//別忘了加m}int main(){ int T; Point P[2500],ch[2500]; scanf("%d",&T); while(T--) { int n,pc=0; double area1=0; scanf("%d",&n); for(int i=0;i<n;i++) { double x,y,w,h,j,ang; scanf("%lf%lf%lf%lf%lf",&x,&y,&w,&h,&j); Point o(x,y); ang=-torad(j); P[pc++]=o+Rotate(Vector(-w/2,-h/2),ang); P[pc++]=o+Rotate(Vector(w/2,-h/2),ang); P[pc++]=o+Rotate(Vector(-w/2,h/2),ang); P[pc++]=o+Rotate(Vector(w/2,h/2),ang); area1+=w*h; //矩形總面積 } int m=ConvexHull(P,pc,ch); double area2=ConvexPolygonArea(ch,m); //凸包面積 printf("%.1lf %%\n",area1*100/area2); } return 0;}
UVA 10652 Board Wrapping(二維凸包)