-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-skyline-problem.cpp
56 lines (45 loc) · 1.18 KB
/
the-skyline-problem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
using namespace std;
struct Event {
bool enter;
int x, h;
bool operator<(const Event ev) const {
if (x != ev.x) return x < ev.x;
if (enter != ev.enter) return enter;
if (enter == ev.enter && enter) return h > ev.h;
return h < ev.h;
}
};
class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<Event> events;
for (const auto& input : buildings) {
const int x1 = input[0];
const int x2 = input[1];
const int h = input[2];
events.emplace_back(true, x1, h);
events.emplace_back(false, x2, h);
}
sort(events.begin(), events.end());
multiset<int> curr;
vector<vector<int>> result;
const auto curr_height = [&]() -> int {
return curr.empty() ? 0 : *prev(curr.end());
};
for (const auto& [enter, x, h] : events) {
if (enter) {
if (curr_height() < h) {
result.emplace_back(vector<int>{x, h});
}
curr.emplace(h);
} else {
curr.erase(curr.find(h));
if (curr_height() < h) {
result.emplace_back(vector<int>{x, curr_height()});
}
}
}
return result;
}
};