发现 ABC 的 F 都好爱考字符串动态规划。
题面翻译
给定字符串 ,将 中的若干字符替换,让 中的 ABC 字符组合数量比原来增加 个,求最少替换数。
好 DP 的 DP。
考虑动态规划
由于 ,最后时间复杂度肯定是一个类似 这样的动态规划。
先考虑无解情况。整个字符串最多能容纳多少个不重叠的 ABC ?每 3 个字符最多 1 个,上限为 。 设原串已有 个 ABC,若 ,直接无解。
观察一下,匹配状态只有 3 种,我们只关心当前后缀匹配 ABC 到哪一步。…
当 为 2 且当前字符选为 C 时,会新生成 1 个 ABC 子串。
再观察, 很小,我们只需要记录累计新增了多少个 ABC,最多存到 即可,超过 不用记录。
可以导出 DP 定义了。
令 为处理到第 位时,累计净新增 个 ABC、当前后缀匹配状态为 ,所需的最小修改代价。初始设全零的位置为 0,其余设为无穷大。
状态转移可以遍历上一层所有合法状态,枚举当前位置 和改成的字符 ,计算代价 ,新匹配状态 和本次新增 。
对于之前位置 ,我们枚举 4 个候选字符 A、B、C、X 就行,其中 X 代表非 A 或 B 或 C 的任意大写字母。
计算修改代价 时, 选 A 或 B 或 C,仅当 s [i] 等于该字符 为 0 ,否则为 1; 选 X,当 s [i] 不是 A 或 B 或 C 时 为 0,否则为 1。
新匹配状态 和本次新增 要简单讨论一下。
若 且 ,拼接出了完整 ABC , 设为 1, 设为 0。
若 ,设 为 1,无新增, 设为 0。
若 且 ,拼接了 AB,新状态 为 2,无新增, 设为 0。
其余情况设 0, 为 0。
如果令 为原串中 位置是否是 ABC 的结束位(原串自带的 ABC,会抵消新增计数), 净新增数量 。
解释一下,本次新造 个 ABC,但原串这里本来就有 个,净增加为 。
当前枚举仅当 时合法,转移公式为 。
你可以滚动数组。
最后贴上代码
代码
#include<bits/stdc++.h>
#define ll long long
#define re register
using namespace std;
const int INF=1e9;
int T,n,k,orig_cnt;
char s[300005];
bool orig_end[300005];
int dp[2][12][3];
inline void ckmin(re int &a,re int b){if(b<a)a=b;}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin>>T;
while(T--){
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin.getline(s+1,300004);
n=strlen(s+1);
cin>>k;
re int max_possible=n/3;
orig_cnt=0;
for(re int i=1;i<=n;i++)orig_end[i]=false;
for(re int i=3;i<=n;i++){
if(s[i-2]=='A'&&s[i-1]=='B'&&s[i]=='C'){
orig_end[i]=true;
orig_cnt++;
}
}
if(orig_cnt+k>max_possible){
cout<<-1<<"\n";
continue;
}
for(re int j=0;j<=k;j++)
for(re int st=0;st<3;st++)
dp[0][j][st]=INF;
dp[0][0][0]=0;
re int cur=0,nxt=1;
const char chars[]={'A','B','C','X'};
for(re int i=1;i<=n;i++){
for(re int j=0;j<=k;j++)
for(re int st=0;st<3;st++)
dp[nxt][j][st]=INF;
for(re int ci=0;ci<4;ci++){
re char c=chars[ci];
re int cost;
if(c=='X')cost=(s[i]!='A'&&s[i]!='B'&&s[i]!='C')?0:1;
else cost=(s[i]==c)?0:1;
for(re int j=0;j<=k;j++){
for(re int st=0;st<3;st++){
if(dp[cur][j][st]>=INF)continue;
re int formed=0,ns=0;
if(st==2&&c=='C'){formed=1;ns=0;}
else if(c=='A'){ns=1;}
else if(st==1&&c=='B'){ns=2;}
else{ns=0;}
re int was_orig=orig_end[i]?1:0;
re int nj=j+formed-was_orig;
if(nj>=0&&nj<=k)ckmin(dp[nxt][nj][ns],dp[cur][j][st]+cost);
}
}
}
cur^=1;nxt^=1;
}
re int ans=INF;
for(re int st=0;st<3;st++)ckmin(ans,dp[cur][k][st]);
if(ans>=INF)cout<<-1<<"\n";
else cout<<ans<<"\n";
}
return 0;
}