题意:
解法:
显然区间dp,
令d[i][j]表示区间[i,j]涂成目标颜色的最小次数.
转移有两种:
1.[i,j]由两个区间[i,k]和[k+1][j]组合而来,那么
此时转移方程为:
d[i][j]=min(d[i][j],d[i][k]+d[k+1][j]),
其中k在[i,j-1]范围内.
2.如果s[i]=s[j],那么s[i]和s[j]可以通过同一次涂色完成,
即先将[i,j]涂色成s[i],然后继续操作[i+1,j-1],
此时转移方程为:
d[i][j]=min(d[i][j],d[i+1][j]),
d[i][j]=min(d[i][j],d[i][j-1]).
code:
#include <bits/stdc++.h>
#define int long long
#define PI pair<int,int>
using namespace std;
const int maxm=2e6+5;
char s[maxm];
int d[55][55];
int n;
void solve(){
cin>>(s+1);
n=strlen(s+1);
for(int len=1;len<=n;len++){
for(int i=1;i<=n;i++){
int j=i+len-1;
if(j>n)break;
if(len==1)d[i][j]=1;
else if(len==2){
d[i][j]=2;
if(s[i]==s[j])d[i][j]=1;
}else{
d[i][j]=len;
for(int k=i;k<j;k++){
d[i][j]=min(d[i][j],d[i][k]+d[k+1][j]);
}
if(s[i]==s[j]){
d[i][j]=min(d[i][j],d[i+1][j]);
d[i][j]=min(d[i][j],d[i][j-1]);
}
}
}
}
cout<<d[1][n]<<endl;
}
signed main(){
ios::sync_with_stdio(0);
solve();
return 0;
}