poj 1159 Palindrome 【LCS】

任意门:http://poj.org/problem?id=1159

 

解题思路:

LCS + 滚动数组

 

AC code:

#include <cstdio>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
const int MAXN = 5e3+10;

char a[MAXN], b[MAXN];
int dp[3][MAXN];

int main()
{
    int len;
    scanf("%d", &len);
    scanf("%s", a+1);
    for(int i = len; i >= 1; i--)
        b[i] = a[len-i+1];

    for(int i = 1; i <= len; i++)
    {
        for(int j = 1; j <= len; j++){
            if(a[i] == b[j]){
                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]);
            }
        }
    }
    int ans = len-dp[len%2][len];
    printf("%d\n", ans);

    return 0;
}

 

posted @ 2019-02-27 20:31  莜莫  阅读(123)  评论(0编辑  收藏  举报