a720中等排序區間與最早最大空隙
CPE:Longest Nap (UVa 10191)
掃描忙碌區間的聯集,求工作日內最長空檔。
解題思路
把 hh:mm 換成分鐘,再依開始時間排序。cursor 初值為 600,代表目前忙碌聯集已覆蓋到的最晚時間。處理 [s,e] 前,若 s>cursor,便找到 [cursor,s] 空檔;之後以 max(cursor,e) 更新,可同時處理行程重疊。
只在空檔長度嚴格變大時更新答案,排序掃描便會保留同長時最早者。最後再檢查 cursor 到 1080 的空檔。行程說明可能有空白,逐行只解析前兩個時間。讀至 EOF,依 Day #d 格式輸出,滿 60 分鐘使用 hours and minutes,即使 1 也不改單數。
Step-by-step animation
示意:11–12 點、13–14 點
步驟 1 / 3
第一空檔
10:00 到 11:00 有 60 分鐘。
600
660
720
- best
- 60
- start
- 600
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int minute(string s) {
return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3, 2));
}
int main() {
int n, day = 0;
string line;
while (cin >> n) {
getline(cin, line);
vector<pair<int, int>> a;
for (int i = 0; i < n; ++i) {
getline(cin, line);
istringstream in(line);
string s, e;
in >> s >> e;
a.push_back({minute(s), minute(e)});
}
sort(a.begin(), a.end());
a.push_back({1080, 1080});
int cur = 600, best = -1, start = 600;
for (auto [s, e] : a) {
if (s - cur > best) {
best = s - cur;
start = cur;
}
cur = max(cur, e);
}
cout << "Day #" << ++day << ": the longest nap starts at " << setfill('0') << setw(2)
<< start / 60 << ':' << setw(2) << start % 60 << setfill(' ') << " and will last for ";
if (best >= 60)
cout << best / 60 << " hours and ";
cout << best % 60 << " minutes.\n";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。