a352中等有界時間差分與同時上課數

TOI 2019/03 潛力組:教室配置

面對千萬門課程,以固定時間軸求包含原有教室的最少總數。

前往題目練習 →回報教學錯誤設 U=10^7,時間 O(N+U),空間 O(U)。C++ int 與 Python array('i') 各約 40 MB 儲存差分;逐行讀入避免把千萬行同時留在記憶體。

解題思路

課程 [S,E) 在 S 開始使用一間教室、在 E 釋放。同一時間下課即可接著上課,所以結束端必須排除。用 delta[S]++、delta[E]--,掃描時間時累加,就得到每個時間點同時上課的門數。輸入可達 10^7 門,但時間上界同樣只有 10^7−1,直接做差分比儲存全部區間後排序更適合。

任何時刻同時進行 c 門課都至少需要 c 間教室,因此最大同時數是下界;按開始時間安排課程,若當下有空教室就重用,否則新增,每次新增都代表同時數創新高,所以此下界可達。系上原本已有一間教室,N=0 時仍有一間,答案為 max(1,最大同時數)。程式只掃到讀到的最大結束時間。

Step-by-step animation

小例 [0,2)、[1,3)、[2,4)

回報動畫錯誤
步驟 1 / 3

時間 0

第一門開始,使用一間。

t0:+1
t1:+1
t2:0
t3:-1
t4:-1
同時數
1
最大值
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    const int U = 10000000;
    vector<int> delta(U);
    int last = 0;
    for (int i = 0, s, e; i < n; i++) {
        cin >> s >> e;
        ++delta[s];
        --delta[e];
        last = max(last, e);
    }
    int current = 0, answer = 1;
    for (int t = 0; t <= last; t++) {
        current += delta[t];
        answer = max(answer, current);
    }
    cout << answer << '\n';
}

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

更多