a289中等至多 K 種元素的雙指標視窗
TOI 2023/04 潛力組:收購土地
維護地主出現次數,以線性移動找到最長合法連續土地。
解題思路
令左右指標夾住目前土地,字典記錄每位地主在視窗內的出現次數。右端加入新土地,若某地主次數從 0 變 1,種類數加一。當種類數超過 K,持續移除最左土地,直到恢復合法;只有次數從 1 變 0 才能刪掉一種地主。
右端固定時,左端停在第一個合法的位置,故目前視窗是以該右端結束的最長合法區段。此前被排除的左端,在加入更多土地後也不可能重新變合法,因此左端不必倒退。每個位置各加入、移除至多一次,取所有右端的最大長度即為答案。
Step-by-step animation
公開範例:K=2
步驟 1 / 3
前 3 塊合法
[1,2,2] 只有兩位地主。
1
2
2
3
2
4
4
- 左端
- 1
- 最長
- 3
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<int> a(n);
for (int &x : a)
cin >> x;
unordered_map<int, int> count;
count.reserve(n * 2);
int l = 0, ans = 0;
for (int r = 0; r < n; r++) {
++count[a[r]];
while ((int)count.size() > k) {
int x = a[l++];
if (--count[x] == 0)
count.erase(x);
}
ans = max(ans, r - l + 1);
}
cout << ans << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。