1513 hdu Palindrome 滚动数组+LCS

点击打开题目链接

由于单纯地求LCS会使得运行超时,因此需要想办法减少开支;

可以想到0-1背包问题是如何由二维减少到一维的,事实上,我们最后只需要计算的最后几个解,因此没有必要把每一步计算结果都储存起来,所以选用滚动数组来做;

最后求的dp[n%2][n]lcs长度,n - dp[n%2][n]即为所求:

#include<iostream>
#include<cstring>
#include <algorithm>

using namespace std;

#define MAX(a,b) (a > b ? a : b)

const int MAXN = 5010;

char str1[MAXN],str2[MAXN];
int dp[2][MAXN];
int n;

void slove()
{
     int i,j;
     strcpy(str2,str1);
     //strrev(str2,str2+n);
     reverse(str2,str2+n);
     memset(dp,0,sizeof(dp));
     for(i = 1; i <= n; ++i)
     {
          for(j = 1; j <= n; ++j)
          {
               if(str1[ i-1 ] == str2[ j-1 ])
               {
                    dp[i%2][j] = dp[(i-1)%2][j-1] + 1;
               }
               else
               {
                    dp[i%2][j] = MAX(dp[(i-1)%2][j],dp[i%2][j-1]);
               }
          }
     }
     cout<<n-dp[n%2][n]<<endl;
}



int main()
{
     while(cin>>n)
     {
          cin>>str1;
          slove();
     }
     return 0;
}


 

你可能感兴趣的:(dp,lcs,滚动数组)