emmm...好难的一道dp
其实本质是两次dp.第一次求出都不相等时候的最优解, 第二次在求出两串有相同时的更优的解.
https://blog.csdn.net/hndu__lz/article/details/52167981
这位讲的不错, 可以去看看.
1 #include <cstdio>
2 #include <cstring>
3 #include <iostream>
4 #include <algorithm>
5 using namespace std;
6 const int MAXN = 1e2 + 20;
7
8 char s[MAXN], t[MAXN];
9 int f[MAXN][MAXN], g[MAXN];
10 int N;
11
12 int main()
13 {
14 while(scanf("%s
%s", s, t) == 2)
15 {
16 N = strlen(s);
17 for(int i = 0; i < N; i++) f[i][i] = 1;
18
19 for(int len = 1; len < N; len++)
20 for(int l = 0; l + len < N; l++){
21 int r = l + len;
22 f[l][r] = f[l + 1][r] + 1;
23
24 for(int k = l + 1; k <= r; k++)
25 if(t[l] == t[k]) f[l][r] = min(f[l][r], f[l + 1][k] + f[k + 1][r]);
26 }
27
28 for(int r = 0; r < N; r++)
29 {
30 g[r] = f[0][r];
31 if(s[r] == t[r]) g[r] = (r == 0) ? 0 : g[r - 1];
32 else
33 for(int l = 0; l < r; l++) g[r] = min(g[r], g[l] + f[l + 1][r]);
34 }
35 cout<<g[N - 1]<<endl;
36 }
37 return 0;
38 }