a406中等線段物件模擬・格點聯集面積
APCS 2021/11:動線安排 (ZeroJudge g596)
保留每條線的兩個木樁端點,依操作刪除完整線段,再計算占用格聯集。
這題在學什麼
只保存每格是否有線,會在拆線時遺失端點關係,也難以保留交叉的另一條線。改用木樁集合和線段列表,每條線都記錄兩個端點。加入木樁時,先刪掉所有包含新格的線段,再向四個方向各找最近木樁,新增四方向中實際存在的連線。
移除木樁時,僅刪掉以該木樁為端點的線,並移除木樁;不額外連接其兩側。線段可跨過其他方向的線,但新木樁插在線上時,原整條線必須先拆除,不能只擦掉該格。
每次操作後重新建立 m×n 的布林占用格,先標記木樁,再標記每條水平或垂直線的所有格,最後數 1。多條線交叉仍只標記一次,且重建可自然保留沒被拆掉的交叉線。h≤200、邊長≤100,這樣直接模擬足夠;所有存活線皆由先前加入動作產生,所以線段數至多 4h。
Step-by-step animation
公開範例一:矩形、延伸、移除中央木樁
步驟 1 / 4
前三次加入
(0,0) 接 (0,2),再由 (0,2) 垂直接 (2,2),共占 5 格。
●─●..
..│..
..●..
- 面積
- 5
- 最大面積
- 5
#include <bits/stdc++.h>
using namespace std;
struct Segment {
int r1, c1, r2, c2;
};
bool contains(const Segment& e, int r, int c) {
if (e.r1 == e.r2) return r == e.r1 && e.c1 <= c && c <= e.c2;
return c == e.c1 && e.r1 <= r && r <= e.r2;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int rows, cols, h;
cin >> rows >> cols >> h;
set<pair<int, int>> stakes;
vector<Segment> edges;
int maximum = 0, area = 0;
while (h--) {
int r, c, operation;
cin >> r >> c >> operation;
vector<Segment> kept;
for (auto e : edges) {
bool remove = operation == 0 ? contains(e, r, c)
: (e.r1 == r && e.c1 == c) || (e.r2 == r && e.c2 == c);
if (!remove) kept.push_back(e);
}
edges.swap(kept);
if (operation == 0) {
array<pair<int, int>, 4> nearest;
nearest.fill({-1, -1});
int distance[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
for (auto [a, b] : stakes) {
int direction = -1, d = 0;
if (b == c && a < r) { direction = 0; d = r - a; }
if (b == c && a > r) { direction = 1; d = a - r; }
if (a == r && b < c) { direction = 2; d = c - b; }
if (a == r && b > c) { direction = 3; d = b - c; }
if (direction != -1 && d < distance[direction]) {
distance[direction] = d;
nearest[direction] = {a, b};
}
}
for (auto point : nearest) {
if (point.first == -1) continue;
auto a = min(point, pair<int,int>{r, c});
auto b = max(point, pair<int,int>{r, c});
edges.push_back({a.first, a.second, b.first, b.second});
}
stakes.insert({r, c});
} else {
stakes.erase({r, c});
}
vector<vector<bool>> occupied(rows, vector<bool>(cols, false));
for (auto [a, b] : stakes) occupied[a][b] = true;
for (auto e : edges) {
if (e.r1 == e.r2) {
for (int b = e.c1; b <= e.c2; ++b) occupied[e.r1][b] = true;
} else {
for (int a = e.r1; a <= e.r2; ++a) occupied[a][e.c1] = true;
}
}
area = 0;
for (const auto& row : occupied) {
for (bool used : row) area += used;
}
maximum = max(maximum, area);
}
cout << maximum << '\n' << area << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。