Description
给出两个字符串 和 ,每次可以对字符串 进行以下三种操作的一种:
在 字符串的第 个字符后面插入字符 ,
删去 字符串的第 个字符,
替代 字符串的第 个字符为 ,
问至少需要多少次操作可以使得 字符串变成 字符串,输出每步操作
Input
输入两个串长不超过 且只由大写字母组成的字符串 和
Output
输出最少操作次数和每步操作
Sample Input
ABA
ABBBA
Sample Output
2
INSERT 3 B
INSERT 4 B
Solution
以 表示 的前 个字符匹配 的前 个字符至少需要的操作数,根据第 个字符采取的操作有转移:
即当前步相同可以不操作,不相同可以替换,或者删去 ,或者在 后加上
至于输出方案,只需看当前步状态是哪个前继状态转移过来的即可
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=1002;
int n,m,dp[maxn][maxn];
char a[maxn],b[maxn];
void output(int x,int y,int num)
{
if(num==0)return ;
if(x>=1&&y>=1&&dp[x-1][y-1]+(a[x]==b[y]?0:1)==dp[x][y])
{
output(x-1,y-1,num-(a[x]==b[y]?0:1));
if(a[x]!=b[y])printf("REPLACE %d %c\n",y,b[y]);
}
else if(x>=1&&dp[x-1][y]+1==dp[x][y])
{
output(x-1,y,num-1);
printf("DELETE %d\n",y+1);
}
else if(y>=1&&dp[x][y-1]+1==dp[x][y])
{
output(x,y-1,num-1);
printf("INSERT %d %c\n",y,b[y]);
}
}
int main()
{
scanf("%s%s",a+1,b+1);
n=strlen(a+1),m=strlen(b+1);
for(int i=0;i<=n;i++)
for(int j=0;j<=m;j++)
if(i&&j)dp[i][j]=INF;
else dp[i][j]=max(i,j);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
dp[i][j]=min(dp[i][j],dp[i-1][j-1]+(a[i]==b[j]?0:1));//replace
dp[i][j]=min(dp[i][j],dp[i-1][j]+1);//delete
dp[i][j]=min(dp[i][j],dp[i][j-1]+1);//insert
}
printf("%d\n",dp[n][m]);
output(n,m,dp[n][m]);
return 0;
}