a124困難枚舉主角・雙指標限制其他字母
TOI 2026/03 潛力組:紙膠帶
正確處理超限字母指定分數的規則,用線性滑窗枚舉主角。
解題思路
固定某字母 c 當候選主角,讓它的次數不限,但其他字母不得超過各自上限,且窗口最多三種字母。每個右端點加入新字母後,只要種類超過三種或有非主角超限,就右移左端點直到合法。次數、種類數及超限的非主角種數都可在加入、刪除一字時 O(1) 更新;字串中未出現的字母不可能成為主角,可以略過。
對固定右端點,最左的合法左端點給出最多的 c,任何更短窗口都不可能含更多 c。若此最大窗口不足三種,縮短也不會變成三種;恰三種時用 c 的次數更新答案。若 c 超限,它正是唯一超限字母,分數等於其次數;若 c 未超限,三者皆合法,真實分數至少為 c 的次數。另一方面,每個漂亮片段取其真正主角 c,都會被這次滑窗涵蓋或改善,因此枚舉 26 個 c 後所得最大值恰為答案。
Step-by-step animation
公開範例 aaabbc,所有上限為 1,固定 b 為主角
步驟 1 / 3
右端到第三個 a
a 不是主角,不能超過 1;左端移到第三個 a,窗口只剩 a。
a已刪
a已刪
a
b
b
c
- 窗口
- a
- 種類
- 1
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> limit(26);
for (int &x : limit)
cin >> x;
string s;
cin >> s;
int answer = 0;
for (int hero = 0; hero < 26; ++hero) {
vector<int> count(26, 0);
int left = 0, kinds = 0, bad = 0;
for (int right = 0; right < n; ++right) {
int x = s[right] - 'a';
if (count[x]++ == 0)
++kinds;
if (x != hero && count[x] == limit[x] + 1)
++bad;
while (kinds > 3 || bad) {
int y = s[left++] - 'a';
if (y != hero && count[y] == limit[y] + 1)
--bad;
if (--count[y] == 0)
--kinds;
}
if (kinds == 3)
answer = max(answer, count[hero]);
}
}
cout << answer << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。