a696中等最小堆排程與同時事件排序
CPE:Argus (UVa 1203)
只維護每個查詢下一次發生時間,不逐秒模擬。
解題思路
每個查詢初次回傳於period秒,此後是2period、3period…。最小堆存 (nextTime,id,period),依時間優先、編號次之排序,堆頂就是目前尚未輸出的最早回傳。所有查詢同時登記,不存在登記時間偏移。
取出堆頂並輸出id,再把它的nextTime加period後放回,其他查詢完全不動。這維持每個查詢恰有一次未來候選事件,因此可依序列出前K次,且時間相同時小id先出。Register讀至#,再讀K;每次結果單獨一行,不加時間。
Step-by-step animation
示意:查詢1週期2,查詢2週期3
步驟 1 / 3
第一次
時間2取出查詢1,回填時間4。
(2,id1)
(3,id2)
- 輸出
- 1
#include <iostream>
#include <queue>
#include <tuple>
#include <vector>
#include <functional>
#include <string>
using namespace std;
int main() {
using Event = tuple<long long, int, int>;
priority_queue<Event, vector<Event>, greater<Event>> heap;
string command;
while (cin >> command && command != "#") {
int id, period;
cin >> id >> period;
heap.push({period, id, period});
}
int k;
cin >> k;
while (k--) {
auto [time, id, period] = heap.top();
heap.pop();
cout << id << '\n';
heap.push({time + period, id, period});
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。