b459中等

冷鏈連續運送

運用雙單調佇列與非負耗能滑動窗,正確求解本題並處理邊界情況。

解題思路

右端加入一箱,以兩個單調佇列記溫度最大與最小,另記耗能總和。

只要極差>D 或總耗能>B 就移動左端、移除耗能與過期佇列索引。

耗能非負、極差對擴張不減,因此縮到首次合法後,留下的是此右端最長合法段;逐右端取最大長度。

時間 O(N),空間 O(N)。

Step-by-step animation

教學例子:範例前3箱溫度4、7、5,極差3、耗能7。

回報動畫錯誤
步驟 1 / 3

步驟 1

範例前3箱溫度4、7、5,極差3、耗能7。

4
7
5
狀態
3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long D, B;
    cin >> n >> D >> B;
    vector<long long> t(n), c(n);
    for (int i = 0; i < n; i++)
        cin >> t[i] >> c[i];
    deque<int> mn, mx;
    int l = 0, ans = 0;
    long long s = 0;
    for (int r = 0; r < n; r++) {
        s += c[r];
        while (!mn.empty() && t[mn.back()] >= t[r])
            mn.pop_back();
        while (!mx.empty() && t[mx.back()] <= t[r])
            mx.pop_back();
        mn.push_back(r);
        mx.push_back(r);
        while (l <= r && (s > B || t[mx.front()] - t[mn.front()] > D)) {
            s -= c[l++];
            while (!mn.empty() && mn.front() < l)
                mn.pop_front();
            while (!mx.empty() && mx.front() < l)
                mx.pop_front();
        }
        ans = max(ans, r - l + 1);
    }
    cout << ans << '\n';
}

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

更多