一、题目
二、解决方案
1.直接法
1)代码
#include<iostream>
#include<stdio.h>
#include <iomanip>
#include<math.h>
using namespace std;
class Rect
{
private:
int x1;
int x2;
int y1;
int y2;
public:
Rect(int a, int b, int c, int d)
{
x1 = a;
y1 = b;
x2 = c;
y2 = d;
}
int BigX()
{
if (x1 > x2)
{
return x1;
}
else
{
return x2;
}
}
int BigY()
{
if (y1 > y2)
{
return y1;
}
else
{
return y2;
}
}
int SmallY()
{
if (y1 < y2)
{
return y1;
}
else
{
return y2;
}
}
int SmallX()
{
if (x1 < x2)
{
return x1;
}
else
{
return x2;
}
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Rect a(x1, y1, x2, y2);
cin >> x1 >> y1 >> x2 >> y2;
Rect b(x1, y1, x2, y2);
int w = 0;
if (a.SmallY() < b.BigY())
{
if (a.SmallX() < b.BigX())
{
w = 1;
}
else if (a.BigX() > b.SmallX())
{
w = 1;
}
}
else if (a.BigY() > b.SmallY() && a.SmallY() < b.SmallY())
{
if (a.SmallX() < b.BigX())
{
w = 1;
}
else if (a.BigX() > b.SmallX())
{
w = 1;
}
}
if (w == 1)
{
cout << "overlapped" << endl;
}
if (w == 0)
{
cout << "not overlapped" << endl;
}
}
}
2)思路
采用分步判断,先判断关于y轴在重叠时的两种情况,再在每一次判断后加入关于x轴重叠两种情况的判断。
2.反向
1)代码
#include <iostream>
using namespace std;
typedef struct Rect {
Rect(int x, int y, int width, int height)
: x(x), y(y), width(width), height(height)
{}
int x;
int y;
int width;
int height;
} Rect;
bool isOverlap(const Rect& rc1, const Rect& rc2)
{
if (rc1.x + rc1.width > rc2.x &&
rc2.x + rc2.width > rc1.x &&
rc1.y + rc1.height > rc2.y &&
rc2.y + rc2.height > rc1.y
)
return true;
else
return false;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Rect rc1(x1, y1, x2, y2);
cin >> x1 >> y1 >> x2 >> y2;
Rect rc2(x1, y1, x2, y2);
if (isOverlap(rc1, rc2))
cout << "overlapped" << endl;
else
cout << "not overlapped" << endl;
}
return 0;
}
2)思路
先解决出不重叠的情况,再进行判断。