题目链接:https://www.luogu.com.cn/problem/P1279
思路:
确定状态dp(i,j)表示字符串s1是1~i,s2是1~j,所以可以要更新dp(i,j)有三种状态,
dp(i,j) = dp(i-1,j) + k;
dp(i,j) = dp(i,j-1) + k;
dp(i,j) = dp(i-1,j-1) + abs(s1[i] - s2[j]);
得到不断更新求出最小值就是最终的答案。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2002;
int dp[N][N] = {0},k;
char s1[N],s2[N];
int main(void)
{
scanf("%s%s%d",s1+1,s2+1,&k);
int l1 = strlen(s1+1),l2 = strlen(s2+1);
for(int i=1;i<=l1;i++) dp[i][0] = dp[i-1][0] + k;
for(int i=1;i<=l2;i++) dp[0][i] = dp[0][i-1] + k;
for(int i=1;i<=l1;i++)
{
for(int j=1;j<=l2;j++)
{
dp[i][j] = min(min(dp[i-1][j] + k ,dp[i][j-1] + k),dp[i-1][j-1] + abs(s1[i] - s2[j]));
}
}
printf("%d\n",dp[l1][l2]);
return 0;
}