解題思路
矩形內部不重疊,因此相接處必在邊界。先以四個角的座標合併共角矩形;再把左右邊依 x 分組、上下邊依 y 分組。同一座標中只需比較朝向相反的邊,其投影區間有交集就代表接觸,包含端點落在另一條邊內的 T 字接點。
同方向的邊投影內部不會重疊,否則兩矩形內部也會重疊,所以兩組區間排序後可用雙指標列出接觸:每次移動右端較早結束的一邊。相同端點的額外角落關係已由角座標處理。並查集在根保存總面積,每次合併相加,最後取最大根面積;多筆資料讀至 EOF。
Step-by-step animation
示意:三片面積 4、2、1 的石板
步驟 1 / 3
建立面積
A=(0,0,2,2)、B=(2,1,1,2)、C=(3,3,1,1)。
A:4
B:2
C:1
- 最大面積
- 4
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
struct DSU {
vector<int> p;
vector<long long> area;
DSU(int n) : p(n), area(n) {
iota(p.begin(), p.end(), 0);
}
int find(int x) {
return p[x] == x ? x : p[x] = find(p[x]);
}
void join(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
if (area[a] < area[b])
swap(a, b);
p[b] = a;
area[a] += area[b];
}
};
using Edge = tuple<int, int, int>; // start, end, rectangle
void sweep(map<int, array<vector<Edge>, 2>> &groups, DSU &d) {
for (auto &[coord, sides] : groups) {
auto &a = sides[0];
auto &b = sides[1];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) {
auto [l, r, id] = a[i];
auto [u, v, jd] = b[j];
if (max(l, u) <= min(r, v))
d.join(id, jd);
if (r < v)
++i;
else
++j;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n) {
DSU d(n);
map<pair<int, int>, int> corners;
map<int, array<vector<Edge>, 2>> vertical, horizontal;
for (int i = 0; i < n; ++i) {
int x, y, w, h;
cin >> x >> y >> w >> h;
d.area[i] = 1LL * w * h;
// Delay all unions until every initial area is assigned.
vertical[x][0].emplace_back(y, y + h, i);
vertical[x + w][1].emplace_back(y, y + h, i);
horizontal[y][0].emplace_back(x, x + w, i);
horizontal[y + h][1].emplace_back(x, x + w, i);
}
for (auto &[x, sides] : vertical)
for (auto &side : sides)
for (auto [lo, hi, id] : side)
for (int y : {lo, hi}) {
auto [it, fresh] = corners.emplace(make_pair(x, y), id);
if (!fresh)
d.join(id, it->second);
}
sweep(vertical, d);
sweep(horizontal, d);
long long best = 0;
for (int i = 0; i < n; ++i)
if (d.find(i) == i)
best = max(best, d.area[i]);
cout << best << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。