题目:
题意:给定两个字符串a,b,保证字符串长度都在1000以内,你可以对A进行三种操作,删除a中任意位置一个字符,在a中任意位置插入一个任意字符,将a中某个位置的字符更换成任意字符,输出最小操作次数,并且输出每次具体操作。
样例:
![](https://img-blog.csdnimg.cn/img_convert/6e86b0fbd22315e92a020e0712b02c14.png)
思路:
首先排除暴力搜索,肯定会超时,没有其他思路的情况考虑贪心和动态规划,考虑动态规划的做法,本题不仅要输出最少操作次数,还要输出每一步的操作,所以有两种做法,第一种是在dp时记录前驱,另一种是在dp后通过数值的递推关系(得能确定你才能用这种方法)找到之前dp的路径。
将最少操作次数作为目标,线性DP的状态应该是很好设计的:dp[i][j]表示将串a的前i个字符变成串b的前i个字符所需要的最小操作次数。
namo,转移的方式就可以有4种:
串a的第i个和串b的第j个相等,dp[i][j]=dp[i-1][j-1]
如果串a的第i个和串b的第j个不相等:
在串a中插入字符:dp[i][j]=dp[i][j-1]+1
在串a中删除字符:dp[i][j]=dp[i-1][j]+1
在串a中替换字符:dp[i][j]=dp[i-1][j-1]
转移方程就可以写出来了:
dp[i][j]=min(min(dp[i-1][j],dp[i][j-1])+1,dp[i-1][j-1]+(s[0][i]!=s[1][j]));
寻路的话,观察转移方程倒着推就行,不做过多解释,上代码:
AC CODE
#include<iostream>
#include<cmath>
#include<algorithm>
#include<map>
#include<vector>
#include<cstring>
#include<set>
#include<queue>
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 998244353;
const int N = 2E6 + 7;
using namespace std;
ll ksm(ll a,ll b) {ll res=1;a%=mod; while(b){if(b&1)res=res*a%mod;b>>=1;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) {return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b) {return a/gcd(a,b)*b;}
ll inv(ll x) {return ksm(x, mod-2);}
void solve(){
vector<string>s(2);
cin>>s[0]>>s[1];
int n=s[0].size(),m=s[1].size();
s[0]=' '+s[0];s[1]=' '+s[1];
vector<vector<int>>dp(n+1,vector<int>(m+1,0));
for(int i=0;i<=n;i++)dp[i][0]=i;
for(int j=0;j<=m;j++)dp[0][j]=j;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
dp[i][j]=min(min(dp[i-1][j],dp[i][j-1])+1,dp[i-1][j-1]+(s[0][i]!=s[1][j]));
cout<<dp[n][m]<<'\n';
while(n!=0||m!=0){
if(n&&dp[n][m]==dp[n-1][m]+1)cout<<"DELETE "<<n<<'\n',n--;
else if(m&&dp[n][m]==dp[n][m-1]+1)cout<<"INSERT "<<n+1<<' '<<s[1][m]<<'\n',m--;
else if(n&&m){
if(dp[n][m]==dp[n-1][m-1]+1)
cout<<"REPLACE "<<n<<' '<<s[1][m]<<'\n';
n--,m--;
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int t=1;//cin>>t;
while(t--)
solve();
}