题目传送
题意:
思路:
四种子问题:
增 ,删,改,不变
那么定义dp数组俩个状态 : 字符串a的前i个字符转化成字符串的前j个字符所需要的次数
1.保持当前状态 dp[i][j] = dp[i][j]
2.dp[i][j] = dp[i-1][j] a的前i个字符转化成b的前j个字符 等于 把a的前i-1个字符转化成b的前j个字符,那么删一个即可
3.dp[i][j] = dp[i][j-1] a的前i个字符 转化成 b的前j-1个字符 ,那么在此基础上再添一个字符即可
4.改变,那么等于dp[i-1][j-1] + (s1[i] != s2[j]) 如果不同,必须改变
除此之外,还先要预处理dp数组已经确定的状态,dp[i][0] = i ,dp[0][j] = i,全删和全添的状态
考虑dp的基本步骤:
考虑有哪些子问题
考虑dp数组所存的状态(也就是dp数组是怎么实现,这里就是i和j俩种状态)
考虑递推方程式
注意无后效性
AC代码
#include<bits/stdc++.h>
#include<iostream>
#include<stack>
#include<algorithm>
#include<queue>
#include<deque>
#include<vector>
#include<map>
#include<set>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
#define int long long
const int N = 1e4 + 100;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-5;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
int dp[2005][2005];
signed main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
string s1;
string s2;
cin >> s1 >> s2;
int len1 = s1.size(),len2 = s2.size();
s1 = " " + s1,s2 = " " + s2;
for(int i = 0;i < 2005;i++) dp[i][0] = i,dp[0][i] = i;
for(int i = 1;i <= len1;i++)
{
for(int j = 1;j <= len2;j++)
{
dp[i][j] = min({dp[i][j-1]+1,dp[i-1][j]+1,dp[i-1][j-1] + (s1[i] != s2[j])});
}
}
cout << dp[len1][len2] << endl;
}