zju/zoj 1459 String Distance and Transform Process

来源:互联网 发布:广州高勤 java 编辑:程序博客网 时间:2024/06/06 03:36

最长公共子序列+保存修改路径。

表示很无奈得记住了别人的代码,所以……

题解出自:http://hi.baidu.com/gugugupan/blog/item/2e0d27e8dd6bf839b80e2df4.html

有时间自己会给出自己的理解和更详细的转移步骤。

#include <iostream>#include <cstring>#include <cstdio>using namespace std;#define  M 81#define Min(a,b) ((a)<(b)?(a):(b))char s[M],t[M];int n,m,dp[M][M],to[M][M];void outpath(){int p=0;while(n!=0 || m!=0 ){to[n][m]?p++:1;switch(to[n][m]){case 1 : cout<<p<<" Delete "<<n<<endl; break;case 2 : cout<<p<<" Insert "<<n+1<<","<<t[m]<<endl;break;case 3 : cout<<p<<" Replace "<<n<<","<<t[m]<<endl;break;}switch(to[n][m]){case 3 :case 0 : n--,m--;break;case 1 : n--; break;case 2 : m--; break;}}}int main(){while(~scanf("%s %s",s+1,t+1) ){int i,j;n=strlen(s+1);m=strlen(t+1);for(i=1;i<=n;i++){dp[i][0]=dp[i-1][0]+1;to[i][0]=1;}for(j=1;j<=m;j++){dp[0][j]=dp[0][j-1]+1;to[0][j]=2;}for(i=1;i<=n;i++){ for(j=1;j<=m;j++){if(s[i]==t[j]){dp[i][j]=dp[i-1][j-1];to[i][j]=0;}else{dp[i][j]=Min(Min(dp[i][j-1],dp[i-1][j-1]),dp[i-1][j])+1;if(dp[i][j]==dp[i-1][j]+1)to[i][j]=1;if(dp[i][j]==dp[i][j-1]+1)to[i][j]=2;if(dp[i][j]==dp[i-1][j-1]+1)to[i][j]=3;}}}cout<<dp[n][m]<<endl;outpath();}return 0;}