UVA 10453 Make Palindrome

足足跑了2秒啊。。。

贴代码:

View Code
 1 #include <stdio.h>
 2 #include <string.h>
 3 char str[1001];
 4 int dp[1001][1001],p[1001][1001];
 5 int DP(int x,int y)
 6 {
 7     int &ans = dp[x][y];
 8     if(ans != -1)
 9         return ans;
10     if(x >= y)
11     {
12         ans = 0;
13         return ans;
14     }
15     if(str[x] == str[y])
16     {
17         ans = DP(x + 1,y - 1);
18         p[x][y] = 0;
19     }
20     else if(DP(x + 1,y) > DP(x,y - 1))
21     {
22         ans = DP(x,y - 1) + 1;
23         p[x][y] = -1;//取后面
24     }
25     else
26     {
27         ans = DP(x + 1,y) + 1;
28         p[x][y] = 1;//取前面
29     }
30     return ans;
31 }
32 void printans(int x,int y)
33 {
34     if(x > y)
35         return;
36     if(x == y)
37         printf("%c",str[x]);
38     else if(p[x][y] == 0)
39     {
40         printf("%c",str[x]);
41         printans(x + 1,y - 1);
42         printf("%c",str[y]);
43     }
44     else if(p[x][y] == 1)
45     {
46         printf("%c",str[x]);
47         printans(x + 1,y);
48         printf("%c",str[x]);
49     }
50     else
51     {
52         printf("%c",str[y]);
53         printans(x,y - 1);
54         printf("%c",str[y]);
55     }
56 }
57 int main()
58 {
59     while(scanf("%s",str) != EOF)
60     {
61         memset(dp,-1,sizeof(dp));
62         int len = strlen(str);
63         printf("%d ",DP(0,len - 1));
64         printans(0,len - 1);
65         putchar('\n');
66     }
67     return 0;
68 }
posted @ 2012-05-26 21:21  浙西贫农  阅读(223)  评论(0编辑  收藏  举报