CodeForces 56 D.Changing a String(dp)

Description

给出两个字符串 a b ,每次可以对字符串 a 进行以下三种操作的一种:

I N S E R T   p o s   c h : a 字符串的第 p o s 1 个字符后面插入字符 c h 1 p o s | a | + 1

D E L E T E   p o s : 删去 a 字符串的第 p o s 个字符, 1 p o s | a |

R E P L A C E   p o s   c h : 替代 a 字符串的第 p o s 个字符为 c h 1 p o s | a |

问至少需要多少次操作可以使得 a 字符串变成 b 字符串,输出每步操作

Input

输入两个串长不超过 1000 且只由大写字母组成的字符串 a b

Output

输出最少操作次数和每步操作

Sample Input

ABA
ABBBA

Sample Output

2
INSERT 3 B
INSERT 4 B

Solution

d p [ i ] [ j ] 表示 a 的前 i 个字符匹配 b 的前 j 个字符至少需要的操作数,根据第 i 个字符采取的操作有转移:

d p [ i ] [ j ] = m i n ( d p [ i 1 ] [ j 1 ] + ( a [ i ] == b [ j ] ? 0 : 1 ) , d p [ i 1 ] [ j ] + 1 , d p [ i ] [ j 1 ] + 1 )

即当前步相同可以不操作,不相同可以替换,或者删去 a [ i ] ,或者在 a [ i ] 后加上 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;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/80036810