hdu1516 输出修改路径的dp:(优美的倒推)

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 char s1[1005],s2[1005];
 6 int dp[1005][1005];
 7 int main()
 8 {
 9     int len1,len2,i,j,t;
10     while (~scanf("%s%s",s1,s2))
11     {
12         len1=strlen(s1); len2=strlen(s2);
13         for (i=len1;i>=1;i--)
14             s1[i]=s1[i-1];
15         for (i=len2;i>=1;i--)
16             s2[i]=s2[i-1];
17         for (i=0;i<=len1;i++)
18             for (j=0;j<=len2;j++)
19         {
20             if (i==0&&j==0) dp[i][j]=0;
21             else if (i==0) dp[i][j]=j;
22             else if (j==0) dp[i][j]=i;
23             else {
24                 if (s1[i]==s2[j]) dp[i][j]=dp[i-1][j-1];
25                 else dp[i][j]=dp[i-1][j-1]+1;
26                 dp[i][j]=min(dp[i][j],min(dp[i-1][j],dp[i][j-1])+1);
27             }
28         }
29         printf("%d\n",dp[len1][len2]);
30         t=0; i=len1; j=len2;
31         while (i>0||j>0)
32         {
33              if (s1[i]==s2[j]&&dp[i][j]==dp[i-1][j-1]){
34                 i--; j--; continue;
35             }
36             printf("%d ",++t);
37             if (j>0&&dp[i][j]==dp[i][j-1]+1){
38                 printf("Insert %d,%c\n",i+1,s2[j]);
39                 j--;
40             }
41             else if (i>0&&dp[i][j]==dp[i-1][j]+1){
42                 printf("Delete %d\n",i);
43                 i--;
44             }
45             else if (dp[i][j]==dp[i-1][j-1]+1){
46                 printf("Replace %d,%c\n",i,s2[j]);
47                 i--; j--;
48             }
49         }
50     }
51     return 0;
52 }

http://acm.hdu.edu.cn/showproblem.php?pid=1516

posted on 2014-10-31 16:13  xiao_xin  阅读(170)  评论(0编辑  收藏  举报

导航