a839困難事件掃描與活動建築最大高度
CPE:The Skyline Problem (UVa 105)
同座標事件一起處理,只輸出真正的天際線轉折。
解題思路
每棟建築在 L 開始覆蓋、R 結束覆蓋,視為半開區間 [L,R)。高度只可能在這些端點改變,因此把所有事件按 x 排序即可。C++ 用 multiset 保存活動高度,同高度建築必須保留重複計數;Python 用最大堆保存高度與右端點,堆頂到期時才延遲刪除。
對同一個 x,先完成該座標所有開始與結束事件,再求新的最高高度。若與前一段相同就不輸出,避免同座標短暫下降或冗餘轉折;若不同才加入 x、高度。初始有地面高度 0,最後所有建築結束自然回到 0。即使輸入已按 L 排序,結束事件仍需納入掃描;全部數字在一行以空白分隔。
Step-by-step animation
示意:建築 (1,3,4)、(2,5,3)
步驟 1 / 3
x=1
第一棟開始,最高從 0 升到 3,記錄 1 3。
活動:3
1 3
- height
- 3
#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <utility>
using namespace std;
int main() {
map<int, vector<pair<int, int>>> events;
int l, h, r;
while (cin >> l >> h >> r) {
events[l].push_back({h, 1});
events[r].push_back({h, -1});
}
multiset<int> active{0};
int previous = 0;
bool first = true;
for (auto &[x, list] : events) {
for (auto [height, kind] : list) {
if (kind == 1)
active.insert(height);
else
active.erase(active.find(height));
}
int current = *active.rbegin();
if (current != previous) {
if (!first)
cout << ' ';
first = false;
cout << x << ' ' << current;
previous = current;
}
}
cout << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。