UVA 10652 Board Wrapping(二維凸包)

來源:互聯網
上載者:User

標籤:

傳送門

劉汝佳《演算法競賽入門經典》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(二維凸包)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.