POJ 1159 Palindrome (滚动数组 DP)

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

   一个字符串至少添加几个字符才能构成回文字符串

思路:其实和上一题很像 把字符串反过来求最长公共子序列 但是这题卡了空间...

   于是在网上看到滚动数组...

#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>

using namespace std;

int dp[5005];
int pre[5005];
int main(){
    int len;
    string str;
    while(cin>>len>>str)
    {
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=len;i++)
        {
            for(int j=1;j<=len;j++)
            {
                pre[j]=dp[j];
                if(str[i-1]==str[len-j]) 
                    dp[j]=pre[j-1]+1;
                else 
                    dp[j]=max(dp[j],dp[j-1]);
            }
        }
        cout<<len-dp[len]<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/danielqiu/archive/2013/01/30/2883684.html

猜你喜欢

转载自blog.csdn.net/weixin_33836223/article/details/93795292
今日推荐