poj1159 palindrome(动态规划+滚动数组)

题目信息:Palindrome

利用动态规划+滚动数组,主要考虑到字符串比较长;

 1 //Accepted 296K 688MS 
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 int c[2][5002];
 7 char str1[5002],str2[5002];
 8 int LCSLength(int n)
 9 {
10     int i,j;
11     int e=0;
12     memset(c,0,sizeof(c));
13     for(i=1;i<=n;++i)
14     {
15         e=1-e;//这里作为行标记,标示当前计算在第e行 
16         if(e==1)
17         {
18             for(j=1;j<=n;++j)
19             {
20                 if(str1[i-1]==str2[j-1]) c[1][j]=c[0][j-1]+1;
21                 else
22                     c[1][j] =  c[0][j]>c[1][j-1]?c[0][j]:c[1][j-1];
23             }
24         }
25         else
26         {
27             for(j=1;j<=n;++j)
28             {
29                 if(str1[i-1]==str2[j-1]) c[0][j]=c[1][j-1]+1;
30                 else
31                     c[0][j]=c[0][j-1]>c[1][j]?c[0][j-1]:c[1][j];
32             }
33         }
34     }
35     if(e==1) return c[1][n];
36     else return c[0][n];
37 }
38 
39 int main()
40 {
41     int n;
42     cin>>n>>str1;
43     for(int i=0;i<n;++i)//把题目转化成求两个串的最长公共子序列问题 
44         str2[i]=str1[n-i-1];
45     cout<<n-LCSLength(n)<<endl;
46     //system("pause");
47     return 0;
48 }
原文地址:https://www.cnblogs.com/redlight/p/2487654.html