Description
给出两个字符串 a a 和,每次可以对字符串 a a 进行以下三种操作的一种:
在 a a 字符串的第个字符后面插入字符 ch c h , 1≤pos≤|a|+1 1 ≤ p o s ≤ | a | + 1
DELETE pos: D E L E T E p o s : 删去 a a 字符串的第个字符, 1≤pos≤|a| 1 ≤ p o s ≤ | a |
REPLACE pos ch: R E P L A C E p o s c h : 替代 a a 字符串的第个字符为 ch c h , 1≤pos≤|a| 1 ≤ p o s ≤ | a |
问至少需要多少次操作可以使得 a a 字符串变成字符串,输出每步操作
Input
输入两个串长不超过 1000 1000 且只由大写字母组成的字符串 a a 和
Output
输出最少操作次数和每步操作
Sample Input
ABA
ABBBA
Sample Output
2
INSERT 3 B
INSERT 4 B
Solution
以 dp[i][j] d p [ i ] [ j ] 表示 a a 的前个字符匹配 b b 的前个字符至少需要的操作数,根据第 i i 个字符采取的操作有转移:
即当前步相同可以不操作,不相同可以替换,或者删去 a[i] a [ i ] ,或者在 a[i] a [ i ] 后加上 b[j] b [ j ]
至于输出方案,只需看当前步状态是哪个前继状态转移过来的即可
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;
}