uva 10453 - Make Palindrome(dp, 记录路径)

题目

题意: 给一个字符串 ,判断最少插入多少个字符 使字符串成为回文串, 并输出回文串。

思路:先用dp判断需要个数, 再递归输出路径。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <cstdlib>
 6 #include <algorithm>
 7 #define min(a, b)((a)>(b)?(b):(a))
 8 using namespace std;
 9 
10 const int maxn = 1100;
11 char s[maxn];
12 int d[maxn][maxn], len;
13 
14 void show(int a, int b)
15 {
16    if(a==b)
17    {
18        cout<<s[a];
19        return;
20    }
21    if(a>b)
22     return;
23    if(s[a] == s[b])
24    {
25      cout<<s[a];
26      show(a+1, b-1);
27      cout<<s[b];
28    }
29    else
30    {
31      if(d[a+1][b] < d[a][b-1])
32      {
33         cout<<s[a];
34         show(a+1, b);
35         cout<<s[a];
36      }
37      else
38      {
39         cout<<s[b];
40         show(a, b-1);
41         cout<<s[b];
42      }
43    }
44 }
45 int main()
46 {
47     int i, k;
48     while(cin>>s)
49     {
50        len = strlen(s);
51        memset(d, 0, sizeof(d));
52        for(i = 0; i < len-1; i++)
53        if(s[i]!=s[i+1])
54        d[i][i+1] = 1;
55        for(k = 2; k <= len-1; k++)
56        for(i = 0; i <len; i++)
57        {
58           if(i+k<len)
59           {
60             if(s[i] == s[i+k])
61                 d[i][i+k] = d[i+1][i+k-1];
62             else
63                 d[i][i+k] = min(d[i+1][i+k], d[i][i+k-1]) + 1;
64           }
65        }
66        cout<<d[0][len-1]<<" ";
67        show(0, len-1);
68        cout<<endl;
69     }
70     return 0;
71 }

 

posted @ 2014-04-24 10:54  水门  阅读(139)  评论(0编辑  收藏  举报