b461中等

混合樣本達標

運用雙下限的最短合法滑動窗,正確求解本題並處理邊界情況。

解題思路

維護目前窗的總份量與種類頻率。

每加入右端後,只要總和≥S且種類≥D,就用長度更新答案並移除左端,直到不再合法。

非負份量使擴張不破壞下限;每個右端所有可縮短的合法窗均被檢查,所以不漏最短答案。

時間 O(N),空間 O(N),字典期望常數。

Step-by-step animation

教學例子:範例前3筆為1:2、1:5、2:1,總量8、種類2。

回報動畫錯誤
步驟 1 / 3

步驟 1

範例前3筆為1:2、1:5、2:1,總量8、種類2。

2
5
1
狀態
長度3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, D;
    long long S;
    cin >> n >> S >> D;
    vector<long long> t(n), a(n);
    for (int i = 0; i < n; i++)
        cin >> t[i] >> a[i];
    unordered_map<long long, int> cnt;
    int kinds = 0, l = 0, ans = n + 1;
    long long s = 0;
    for (int r = 0; r < n; r++) {
        s += a[r];
        if (++cnt[t[r]] == 1)
            kinds++;
        while (s >= S && kinds >= D) {
            ans = min(ans, r - l + 1);
            s -= a[l];
            if (--cnt[t[l]] == 0)
                kinds--;
            l++;
        }
    }
    cout << (ans > n ? -1 : ans) << '\n';
}

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

更多