题解
题目大意,给ab两个串,每次可以花费1代价将某一段改为一同种字符,问将a改为b的最小代价
先考虑一个空的串变成b的最小次数,再利用a和b相同的单个位置为0合并区间,枚举区间长度枚举区间起点
如果当前区间左右端点相同则次数等于左边少一格或右边少一格的区间次数即d[i][j]=min(d[i][j], d[i + 1][j], d[i][j - 1])
如果左侧或者右侧连着两个相同则次数等于左侧或右侧少一格的次数即d[i][j]=min(d[i][j], d[i+1][j])(左侧连着2个相同)
然后在将ab相同的单个点代价修改为0,重新合并区间
AC代码
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 110;
char a[MAXN], b[MAXN];
int d[MAXN][MAXN]; //区间i到j最少操作次数
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
while (scanf("%s%s", a + 1, b + 1) != EOF)
{
memset(d, 0x3f, sizeof(d));
int n = strlen(a + 1);
for (int i = 1; i <= n; i++)
d[i][i] = 1; //先不利用原串相同 单个字符为1
for (int l = 2; l <= n; l++)
for (int i = 1; i + l - 1 <= n; i++)
{
int j = i + l - 1;
if (b[i] == b[j]) //两端相等等于左侧少1或者右侧少1 变化尽量小 abaca
d[i][j] = min({ d[i][j], d[i + 1][j], d[i][j - 1] });
if (b[i] == b[i + 1]) //左侧相同
d[i][j] = min(d[i][j], d[i + 1][j]); //等于左侧少1格
if (b[j] == b[j - 1]) //右侧
d[i][j] = min(d[i][j], d[i][j - 1]);
for (int k = i; k < j; k++) //合并区间
d[i][j] = min(d[i][j], d[i][k] + d[k + 1][j]);
}
for (int i = 1; i <= n; i++)
if (a[i] == b[i]) d[i][i] = 0; //如果相同单个为0
for (int l = 2; l <= n; l++)
for (int i = 1; i + l - 1 <= n; i++)
{
int j = i + l - 1; //不能再利用左右侧相同 ab bb
for (int k = i; k < j; k++) //合并区间
d[i][j] = min(d[i][j], d[i][k] + d[k + 1][j]);
}
cout << d[1][n] << endl;
}
return 0;
}