解題思路
兩矩形交集的水平長度是max(0,min(x2a,x2b)−max(x1a,x1b)),垂直長度同理,相乘即共同面積S。各自面積為A、B,相加時共同區域被算兩次,所以恰好一人看守為W=A+B−2S。
聯集面積是A+B−S,整片土地固定10000,因此無人看守U=10000−(A+B−S)。S+W+U應等於10000,可作驗算。只在邊或頂點接觸時,至少一軸長度為0,公式自然給出0。輸出Night k: S W U。
Step-by-step animation
示意:(10,10)-(20,20)與(15,15)-(25,25)
步驟 1 / 3
求交集
x與y皆重疊15到20,長5。
寬5
高5
S=25
- A
- 100
- B
- 100
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int T;
cin >> T;
for (int tc = 1; tc <= T; ++tc) {
int a, b, c, d, e, f, g, h;
cin >> a >> b >> c >> d >> e >> f >> g >> h;
int A = (c - a) * (d - b), B = (g - e) * (h - f);
int S = max(0, min(c, g) - max(a, e)) * max(0, min(d, h) - max(b, f));
cout << "Night " << tc << ": " << S << ' ' << A + B - 2 * S << ' ' << 10000 - A - B + S
<< '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。