判断两个矩阵是否重叠

题目描述

给定两个矩阵:

前提:两个矩阵的边均与x轴和y轴平行,即轴对齐的矩形

将第一个矩形记作A,第二个矩形记作B,判断矩形A与矩形B是否重叠(边沿重叠也认为是重叠),如果重叠则返回重叠面积。。

算法分析

反向思考,我们不妨先解决出“不重叠”的情况,即B矩阵,可能在A的左侧、右侧、上侧、下侧。

提交代码:

#include
#include
#include

using namespace std;

struct Rectangle {
	// 左下角x, y
	double x, y, height, width;
	Rectangle(double x, double y, double height, double width) :
		x(x), y(y), height(height), width(width) {}
};

int main()
{
	Rectangle rect1(0, 1, 3, 2);
	Rectangle rect2(2, 0, 2, 2);

	// p1 p2 矩阵1的左下角,右上角点
	// p3 p4 矩阵2的左下角,右上角点
	double p1_x = rect1.x, p1_y = rect1.y;
	double p2_x = p1_x + rect1.width, p2_y = p1_y + rect1.height;
	double p3_x = rect2.x, p3_y = rect2.y;
	double p4_x = p3_x + rect2.width, p4_y = p3_y + rect2.height;

	// 判断是否重叠
	if (p1_y > p4_y || p3_y > p2_y || p4_x < p1_x || p3_x > p2_x) {
		cout << 0 << endl;
		return 0;
	}

	double width = min(p2_x, p4_x) - max(p1_x, p3_x);
	double height = min(p2_y, p4_y) - max(p1_y, p3_y);

	cout << width * height << endl;
	return 0;
}

若对于每个矩形,我们给出它的一对相对顶点的坐标,此时两个矩形的交的面积:

#include
#include
using namespace std;
double max(double x1, double x2);
double min(double x1, double x2);
int main()
{
    double x1, y1, x2, y2, x3, y3, x4, y4, x01, x02, y01, y02;
    cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;
    x01 = max(min(x1, x2), min(x3, x4));
    x02 = min(max(x1, x2), max(x3, x4));
    y01 = max(min(y1, y2), min(y3, y4));
    y02 = min(max(y1, y2), max(y3, y4));
    if (x01 < x02&&y01 < y02)
        printf("%.2f\n", abs(x01 - x02)*abs(y01 - y02));//输出保留两位小数 
    else
        printf("%.2f\n", 0);
    return 0;
}

double max(double x1, double x2) {
    return x1>x2 ? x1 : x2;
}
double min(double x1, double x2) {
    return x1>x2 ? x2 : x1;
}

 

你可能感兴趣的:(OJ真题)