b111中等

111 北二區資訊學科能力競賽(2022)|程式排程模擬

區分時間片內到達與端點到達。

解題思路

維護尚未完成程式的FIFO佇列與下一筆到達索引。隊列為空時把時間跳到下一支程式到達,不逐秒等待。

隊首執行d=min(K,剩餘時間)。先加入所有到達時刻嚴格小於執行結束時刻的新程式;再將仍未完成的隊首放回尾端;最後加入到達時刻恰為結束時刻的程式。

此順序精確保留「時間片用完的程式先於同刻新程式」規則。當目標程式完成,回傳目前時刻減其到達時刻。

若共R個時間片,時間 O(N+R),R≤Σceil(runtime/K),佇列及輸入O(N)。

Step-by-step animation

時間片事件與同刻入列順序|K=2,程式1於1到達需3,程式2於3到達需1。

回報動畫錯誤
步驟 1 / 3

開始

K=2,程式1於1到達需3,程式2於3到達需1。

執行1
時間
1→3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n, k, x;
    cin >> n >> k >> x;
    --x;
    vector<long long> a(n);
    vector<int> r(n);
    for (int i = 0; i < n; i++)
        cin >> a[i] >> r[i];
    queue<int> q;
    long long t = 0;
    int next = 0;
    while (true) {
        if (q.empty()) {
            t = max(t, a[next]);
            while (next < n && a[next] <= t)
                q.push(next++);
        }
        int u = q.front();
        q.pop();
        int d = min(k, r[u]);
        long long end = t + d;
        while (next < n && a[next] < end)
            q.push(next++);
        r[u] -= d;
        t = end;
        if (!r[u] && u == x) {
            cout << t - a[x] << "\n";
            break;
        }
        if (r[u])
            q.push(u);
        while (next < n && a[next] <= t)
            q.push(next++);
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多