解題思路
把到達記為 +1、離開記為 -1,按時間排序。
掃描到一個事件後,累計值就是此時在店內的人數;所有最大值只會在到達時產生,因此沿途取最大即可。
題目保證所有時間互異,不需處理同時抵達與離開的優先順序。
時間 O(n log n),事件及輸入儲存 O(n)。
Step-by-step animation
教學例子:顧客 A 的時段是 [1,8)。
步驟 1 / 3
到達 1
顧客 A 的時段是 [1,8)。
1
- 目前
- 1
- 最大
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pair<int, int>> e;
for (int i = 0, a, b; i < n; i++) {
cin >> a >> b;
e.push_back({a, 1});
e.push_back({b, -1});
}
sort(e.begin(), e.end());
int s = 0, ans = 0;
for (auto [t, d] : e) {
s += d;
ans = max(ans, s);
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。