您的位置:首页 > 移动开发

UVA - 10652 Board Wrapping(计算几何-凸包)

2017-05-18 17:41 423 查看
点击打开题目链接



第一次做计算几何的题,真切感受到数学不好是最致命的,半天连一个角度化弧度都想不出(可以看出我数学有多坨 TAT ),题目本身理解不难,但是需要各种功能函数的实现,组合。计算几何的题以后还是要多做。

题目大意:用一个尽量小的凸多边形包起n块矩形木板,计算木板面积与整个包装面积的百分比。

思路:每块木板的四个点都作为输入,求出的凸包就是包装。

附上AC代码:

#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstdio>

using namespace std;
const int maxn = 600 * 4 + 5;
int T;
int n;
double x, y, w, h, j;
int cnt;
int m;

struct Point {
double _x, _y;
Point(double x=0,double y=0):_x(x),_y(y){}
bool operator <(const Point &P)
{
return _x < P._x || (_x == P._x&&_y < P._y);
}
}P[maxn],ch[maxn];

typedef Point Vector;

Vector operator +(Vector p1, Vector p2) { return Vector(p1._x + p2._x, p1._y + p2._y); }
Vector operator -(Vector p1, Vector p2) { return Vector(p1._x - p2._x, p1._y - p2._y); }
//求旋转向量,rad为逆时针旋转的弧度
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 torad(double deg)
{
return deg / 180 * acos(-1);
}
//求两向量的叉积
double Cross(Vector A, Vector B)
{
return A._x*B._y - A._y*B._x;
}
//计算凸包,返回凸包顶点数
int ConvexHull(Point* p, int n, Point* 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;
}
//计算凸包面积
double PolygonArea(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;
}

int main()
{
ios::sync_with_stdio(false);
cin >> T;
while (T--)
{
double area1 = 0, area2 = 0;
cnt = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> x >> y >> w >> h >> j;
Point o(x, y);
double angle = -torad(j);//因为j是顺时针
P[cnt++] = o + Rotate(Vector(-w / 2, -h / 2), angle);//先旋转从中心出发的向量
P[cnt++] = o + Rotate(Vector(w / 2, -h / 2), angle);
P[cnt++] = o + Rotate(Vector(-w / 2, h / 2), angle);
P[cnt++] = o + Rotate(Vector(w / 2, h / 2), angle);
area1 += w * h;//累加木板的总面积
}
m = ConvexHull(P, cnt, ch);
area2 = PolygonArea(ch, m);
cout << setprecision(1) << fixed << area1 * 100 / area2 << " %" << endl;
}
// system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  凸包 计算几何