Do \ (DP \) title, we have to consider the following points:
\ (1 \) state is defined
\ (2 \) state transition equation
\ (3 \) boundary
\ (4 \) target
Then we analyze in turn.
Status Definitions
According to the meaning of problems, it is very simple:
\ (f_ {i, j} \) represents \ (A \) before the string \ (I \) letters and \ (B \) before the string \ (J \) minimum distance letters.
State transition equation
For \ (f_ {i, j} \) , it will undoubtedly three cases:
\ (1. \) \ (A_i \) and \ (B_j \) a \ (ASCLL \) the difference between the absolute values of the code
\ (2. \) \ (A_i \) corresponds to a space
\ (3. \) \ (B_j \) corresponds to a space
Obviously, the first equation is best to write: \ (. 1-F_ {I, J}. 1-+ | A_i-B_j | \)
And second, because \ (A_i \) corresponding to a space, so that, from a certain state \ (A \) before the string \ (i-1 \) letter of \ (B \) before the string \ (J \) minimum distance push letters.
Therefore, the second equation is: \ (. 1-F_ {I, J} + K \)
Similarly, the third equation is: \ (F_ {I, J-K. 1} + \)
\ (f_ {i, j} \) is the minimum of the three.
boundary
From \ (f_ {i, 0} \) and \ (f_ {0, j} \) start.
Starting defined start, \ (F_ {I, 0} \) represents \ (A \) before the string \ (I \) letters and \ (B \) before the string \ (0 \) minimum distance letters .
Is not that strange?
So we can only default the first letter is zero space, so:
\(f_{i,0}=f{i-1,0}+k\)
About simplification is: \ (F_ {I, I = 0} * K \)
Similarly, \ (F_ {0, J} = J * K \)
aims
Set \ (A \) run length of \ (m \) , \ (B \) run length \ (n-\) , the target is Easy: \ (F_ {m, n-} \)
\(AC\) \(Code\)
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
string a, b;
int m, n, f[2010][2010], k;
int main() {
cin >> a >> b;
cin >> k;
m = a.size(), n = b.size();
a = ' '+a, b = ' '+b;// 因为string下标从零开始,所以利用string加法的特性,开头加空格
for (int i=1; i<=m; i++)
f[i][0] = i*k;
for (int j=1; j<=n; j++)
f[0][j] = j*k;
for (int i=1; i<=m; i++)
for (int j=1; j<=n; j++) {
f[i][j] = 1e9; // 因为要取最小,所以初值要赋大
f[i][j] = min(f[i-1][j-1]+abs(a[i] - b[j]), min(f[i-1][j]+k, f[i][j-1]+k));
//求三者最小值可用min套min
}
cout << f[m][n] << endl;
return 0; // 完结撒花!
}