AT_abc462_f [ABC462F] More ABC 题解
yangshengyue · · 题解
发现 ABC 的 F 都好爱考字符串动态规划。
题面翻译
给定字符串
好 DP 的 DP。
考虑动态规划
由于
先考虑无解情况。整个字符串最多能容纳多少个不重叠的
观察一下,匹配状态只有
当
再观察,
可以导出 DP 定义了。
令
状态转移可以遍历上一层所有合法状态,枚举当前位置
对于之前位置
计算修改代价
新匹配状态
若
若
若
其余情况设
如果令
解释一下,本次新造
当前枚举仅当
你可以滚动数组。
最后贴上代码
:::success[AC code]
#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;
}
:::