poj 1159 Palindrome

题目链接:http://poj.org/problem?id=1159

题目大意:给一个字符串,求这个字符串最少增加几个字符能变成回文。

解题思路:求该字符串与其反串的最长公共子序列(一定是回文)的长度,则所求为:该字符串的长度 - 最长公共子序列的长度。

 1 ///////////////////////////////////////////////////////////////////////////
 2 //problem_id: poj 1159
 3 //user_id: SCNU20102200088
 4 ///////////////////////////////////////////////////////////////////////////
 5 
 6 #include <algorithm>
 7 #include <iostream>
 8 #include <iterator>
 9 #include <iomanip>
10 #include <cstring>
11 #include <cstdlib>
12 #include <string>
13 #include <vector>
14 #include <cstdio>
15 #include <cctype>
16 #include <cmath>
17 #include <queue>
18 #include <stack>
19 #include <list>
20 #include <set>
21 #include <map>
22 using namespace std;
23 
24 ///////////////////////////////////////////////////////////////////////////
25 typedef long long LL;
26 const double PI=acos(-1.0);
27 ///////////////////////////////////////////////////////////////////////////
28 
29 ///////////////////////////////////////////////////////////////////////////
30 //Add Code:
31 int max(int a,int b){
32     return a>b? a:b;
33 }
34 ///////////////////////////////////////////////////////////////////////////
35 
36 int main(){
37     ///////////////////////////////////////////////////////////////////////
38     //Add code:
39     int n,i,j,dp[2][5005];
40     char s[5005],t[5005];
41     scanf("%d%s",&n,s);
42     for(i=0;i<n;i++) t[i]=s[n-i-1];
43     memset(dp,0,sizeof(dp));
44     for(i=1;i<=n;i++){
45         for(j=1;j<=n;j++){
46             if(s[i-1]==t[j-1]) dp[i%2][j]=dp[(i-1)%2][j-1]+1;
47             else dp[i%2][j]=max(dp[i%2][j-1],dp[(i-1)%2][j]);
48         }
49     }
50     printf("%d\n",n-dp[n%2][n]);
51     ///////////////////////////////////////////////////////////////////////
52     return 0;
53 }
54 
55 ///////////////////////////////////////////////////////////////////////////
56 /*
57 Testcase:
58 Input:
59 5
60 Ab3bd
61 Output:
62 2
63 */
64 ///////////////////////////////////////////////////////////////////////////

posted on 2013-08-20 10:25  SCNU20102200088  阅读(127)  评论(0编辑  收藏  举报

导航