開啟章節選單
Restaurant Customers
簡易題敘
一個餐廳有 個顧客,給你他們到跟離開的時間,求人最多的時候有多少客人。
範例測資:
- 輸入
3
5 8
2 4
3 9
- 輸出
2
概念講解
這題跟教學文章上寫的線段覆蓋範例基本上概念一模一樣!
先開一個 vector
紀錄進出時間,pair
的 first
記時間,second
記進()或出()。
vector<pair<int,int>> P; . . . for(int i = 0; i < n; i++){ cin >> l >> r; P.push_back({l, 1}); P.push_back({r, -1}); }
排序之後處理每個線段端點的客人數量加減,每改變一次就要跟答案取max
。
for(auto p : P){ now += p.second; ans = max(ans, now); }
範例程式碼
#include <bits/stdc++.h> using namespace std; #define int long long #define pii pair<int, int> vector<pii> P; int n, l, r, now, ans; signed main(){ cin >> n; for(int i = 0; i < n; i++){ cin >> l >> r; P.push_back({l, 1}); P.push_back({r, -1}); } sort(P.begin(), P.end()); for(auto p : P){ now += p.second; ans = max(ans, now); } cout << ans; }