当前位置: 代码迷 >> 综合 >> CodeForces 56D Changing a String (DP+打印路径)
  详细解决方案

CodeForces 56D Changing a String (DP+打印路径)

热度:17   发布时间:2023-11-15 13:29:34.0

题目链接:http://codeforces.com/problemset/problem/56/D

#include<bits/stdc++.h>
using namespace std;#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))#define pii pair<ll,ll>
#define mk(x,y) make_pair(x,y)const int  maxn =1e3+5;
const int mod=1e9+7;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}char s1[maxn],s2[maxn];
int len1,len2,flag;///标志到底删除还是插入
int dp[maxn][maxn];void backtrace(int x,int y,int flag){if(flag==0) return ;if(dp[x][y]==dp[x][y-1]+1){backtrace(x,y-1,flag-1);printf("INSERT %d %c\n",y,s2[y]);}else if(dp[x][y]==dp[x-1][y]+1){backtrace(x-1,y,flag-1);printf("DELETE %d\n",y+1);}else{backtrace(x-1,y-1,flag-(s1[x]!=s2[y]));if(s1[x]!=s2[y])  printf("REPLACE %d %c\n",y,s2[y]);}
}int main(){scanf("%s%s",s1+1,s2+1);int len1=strlen(s1+1),len2=strlen(s2+1);///长度mst(dp,0xf),dp[0][0]=0;rep(i,1,len1+1) dp[i][0]=i;rep(i,1,len2+1) dp[0][i]=i;///初始化rep(i,1,len1+1) rep(j,1,len2+1){dp[i][j]=min(dp[i-1][j-1]+(s1[i]!=s2[j]),min(dp[i-1][j],dp[i][j-1])+1);}printf("%d\n",dp[len1][len2]);backtrace(len1,len2,dp[len1][len2]);///回溯return 0;
}

 

  相关解决方案