CodeForces 56 D.Changing a String(dp)

202 篇文章 1 订阅

Description

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

INSERT pos ch: a a 字符串的第pos1个字符后面插入字符 ch c h 1pos|a|+1 1 ≤ p o s ≤ | a | + 1

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

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

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

Input

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

Output

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

Sample Input

ABA
ABBBA

Sample Output

2
INSERT 3 B
INSERT 4 B

Solution

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

dp[i][j]=min(dp[i1][j1]+(a[i]==b[j]?0:1),dp[i1][j]+1,dp[i][j1]+1)

即当前步相同可以不操作,不相同可以替换,或者删去 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值