问题描述
平面上有两个矩形,它们的边平行于直角坐标系的X轴或Y轴。对于每个矩形,我们给出它的一对相对顶点的坐标,请你编程算出两个矩形的交的面积。
输入格式
输入仅包含两行,每行描述一个矩形。
在每行中,给出矩形的一对相对顶点的坐标,每个点的坐标都用两个绝对值不超过10^7的实数表示。
在每行中,给出矩形的一对相对顶点的坐标,每个点的坐标都用两个绝对值不超过10^7的实数表示。
输出格式
输出仅包含一个实数,为交的面积,保留到小数后两位。
样例输入
1 1 3 3
2 2 4 4
2 2 4 4
样例输出
1.00
思路:
1、由于输入的点可能是矩形的主对角线的两个顶点,也可能是副对角线的两个顶点,所以对坐标进行排序,统一成矩形的主对角线上的两个顶点,方便判断相离。(也可以直接用重心判断两矩形是否相离,如同判断两个圆是否相离的原理,但是码起来比较长,如果采用这种方法,即可跳过步骤2)
2、判断相离的四种方式,即以第一个矩形为中心,另一个矩形在其四周的相离方式。
3、对输入的四个点的横坐标与纵坐标分别进行升序排序,即x1 > x2 > x3 > x4, y1 > y2 > y3 > y4,(x3 - x2)* (y3 - y2)即为两矩形的相交面积。
注意:一定要用double存储,即使最后精度不是double,中间过程中也可能出现需要double存储的数据,用float会造成精度损失,导致结果偏差,测试数据无法通过。
用重心判断矩阵相离
思路:
1、由于输入的点可能是矩形的主对角线的两个顶点,也可能是副对角线的两个顶点,所以对坐标进行排序,统一成矩形的主对角线上的两个顶点,方便判断相离。(也可以直接用重心判断两矩形是否相离,如同判断两个圆是否相离的原理,但是码起来比较长,如果采用这种方法,即可跳过步骤2)
2、判断相离的四种方式,即以第一个矩形为中心,另一个矩形在其四周的相离方式。
3、对输入的四个点的横坐标与纵坐标分别进行升序排序,即x1 > x2 > x3 > x4, y1 > y2 > y3 > y4,(x3 - x2)* (y3 - y2)即为两矩形的相交面积。
注意:一定要用double存储,即使最后精度不是double,中间过程中也可能出现需要double存储的数据,用float会造成精度损失,导致结果偏差,测试数据无法通过。
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
double x[4];
double y[4];
//freopen("input7.txt","r",stdin);
for(int i = 0; i < 4; i++)
scanf("%lf%lf", &x[i], &y[i]);
sort(x, x + 2);
sort(x + 2, x + 4);
sort(y , y + 2);
sort(y + 2, y + 4);
if(x[1] <= x[2] || x[0] >= x[3] || y[0] >= y[3] || y[1] <= y[2])
printf("%.2lf\n", 0);
else
{
sort(x, x + 4);
sort(y, y + 4);
printf("%.2lf\n", (x[2] - x[1]) * (y[2] - y[1]));
}
return 0;
}
用重心判断矩阵相离
//#define LOCAL
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <iostream>
using namespace std;
#define OA_X (a.x_top + a.x_bottom)/2
#define OA_Y (a.y_top + a.y_bottom)/2
#define OB_X (b.x_top + b.x_bottom)/2
#define OB_Y (b.y_top + b.y_bottom)/2
#define D_X fabs(a.x_top - a.x_bottom)/2 + fabs(b.x_top - b.x_bottom)/2
#define D_Y fabs(a.y_top - a.y_bottom)/2 + fabs(b.y_top - b.y_bottom)/2
struct Coordinate
{
double x_bottom, y_bottom;
double x_top, y_top;
};
bool isCross(Coordinate a, Coordinate b)
{
if(D_X <= fabs(OA_X - OB_X) || D_Y <= fabs(OA_Y - OB_Y))
return false;
return true;
}
double Area(Coordinate a, Coordinate b)
{
if(isCross(a, b) == false)
return 0.00;
double array_x[4], array_y[4];
array_x[0] = a.x_bottom;
array_x[1] = a.x_top;
array_x[2] = b.x_bottom;
array_x[3] = b.x_top;
sort(array_x, array_x+4);
array_y[0] = a.y_bottom;
array_y[1] = a.y_top;
array_y[2] = b.y_bottom;
array_y[3] = b.y_top;
sort(array_y, array_y+4);
return (array_x[2] - array_x[1]) * (array_y[2] - array_y[1]);
}
int main()
{
#ifdef LOCAL
freopen("input5.txt", "r", stdin);
#endif
Coordinate a, b;
double ans;
scanf("%lf%lf%lf%lf", &a.x_bottom, &a.y_bottom, &a.x_top, &a.y_top);
scanf("%lf%lf%lf%lf", &b.x_bottom, &b.y_bottom, &b.x_top, &b.y_top);
ans = Area(a, b);
printf("%.2lf\n", ans);
return 0;
}