杭电oj HDOJ 2056 Rectangles
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2056
Problem Description
Given two rectangles and the coordinates of two points on the diagonals of each rectangle,you have to calculate the area of the intersected part of two rectangles. its sides are parallel to OX and OY .
Input
Input The first line of input is 8 positive numbers which indicate the coordinates of four points that must be on each diagonal.The 8 numbers are x1,y1,x2,y2,x3,y3,x4,y4.That means the two points on the first rectangle are(x1,y1),(x2,y2);the other two points on the second rectangle are (x3,y3),(x4,y4).
Output
Output For each case output the area of their intersected part in a single line.accurate up to 2 decimal places.
题目大意
分别给出两个矩形每个一条对角线的坐标,求这两个矩形重合部分的面积。
解题思路
本题的关键是找出重合部分的长和宽,如果你想确定到底是谁减谁(比如是x3 - x2还是x2 - x3),那么需要考虑的情况就太多了。所以我们要把它的求法抽象出来。
- 易得能完全覆盖已知的两个矩形且保证面积最小的矩形(后面叫做“大矩形”),其长为已知四个横坐标数据中的最大值减最小值,其宽为已知四个纵坐标数据中的最大值减最小值。
- 也易得两个已知矩形的长和宽。
- 那么重合部分的长就等于两个已知矩形的长相加减去那个“大矩形”的长,重合部分的宽等于两个已知矩形的宽相加减去那个“大矩形”的宽。
- 因为我们无法确定输入数据之间的大小关系,所以需要“相减后取绝对值”的操作。
C++代码
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
double x1, y1, x2, y2, x3, y3, x4, y4, x[4], y[4], length, width;
while (cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4) {
x[0] = x1;
x[1] = x2;
x[2] = x3;
x[3] = x4;
y[0] = y1;
y[1] = y2;
y[2] = y3;
y[3] = y4;
// 对横、纵坐标数据进行升序排列
sort(x, x + 4);
sort(y, y + 4);
// 重合部分的长等于两个矩形长的和减去四个横坐标中最大与最小的差
length = fabs(x1 - x2) + fabs(x3 - x4) - (x[3] - x[0]);
// 重合部分的宽与长的求法相同
width = fabs(y1 - y2) + fabs(y3 - y4) - (y[3] - y[0]);
if (length < 0 || width < 0) {
// 不能使用“setiosflags(ios::fixed) << setprecision(2) << 0”!
cout << "0.00" << endl;
}
else {
cout << setiosflags(ios::fixed) << setprecision(2) << length * width << endl;
}
}
return 0;
}
代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!