$$\color{red}{算法}\color{blue}{基础课}\color{purple}{笔记and题解}\color{green}{汇总}$$
设 $f_{i,j}$ 表示 $A_{1 \dots i}$ 变为 $B_{1 \dots j}$ 的最小操作数。
#include <bits/stdc++.h>
using namespace std;
const int N = 1015;
int n, m;
char a[N], b[N];
int f[N][N];
int main() {
scanf("%d %s", &n, (a + 1));
scanf("%d %s", &m, (b + 1));
memset(f, 0x3f3f3f3f, sizeof f);
f[0][0] = 0;
for (int i = 1; i <= n; i++) f[i][0] = i;
for (int i = 1; i <= m; i++) f[0][i] = i;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (a[i] == b[j]) f[i][j] = min(f[i][j], f[i - 1][j - 1]); //直接匹配
else f[i][j] = f[i - 1][j - 1] + 1; //替换其一
f[i][j] = min({f[i][j], f[i - 1][j] + 1, f[i][j - 1] + 1}); //插入删除
}
printf("%d\n", f[n][m]);
return 0;
}