A Subsequence is a sequence obtained by deleting zero or more characters in a string. A Palindrome is a string which when read from left to right, reads same as when read from right to left. Given a string, find the longest palindromic subsequence. If there are many answers to it, print the one that comes lexicographically earliest.
Constraints
Input consists of several strings, each in a separate line. Input is terminated by EOF.
For each line in the input, print the output in a single line.
aabbaabb
computer
abzla
samhita
aabbaa
c
aba
aha
<span style="font-size:18px;">#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
const double PI = acos(-1.0);
const double e = 2.718281828459;
const double eps = 1e-8;
const int MAXN = 1010;
struct str
{
int len;
string s;
} dp[MAXN][MAXN];
char s[MAXN];
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while(scanf("%s", s+1) != EOF)
{
int len = strlen(s+1);
for(int i = 1; i <= len; i++)
{ //初始化
dp[i][i].len = 1;
dp[i][i].s = s[i];
}
for(int k = 2; k <= len; k++) //控制区间大小
{
for(int i = 1, j = k; j <= len; i++, j++) //正推
//for(int i = len-k+1, j = len; i >= 1; i--, j--) //逆推
{
if(s[i] == s[j])
{
dp[i][j].len = dp[i+1][j-1].len+2;
dp[i][j].s = s[i]+dp[i+1][j-1].s+s[j];
}
else
{
if(dp[i][j-1].len > dp[i+1][j].len ||
(dp[i][j-1].len==dp[i+1][j].len&&dp[i][j-1].s<dp[i+1][j].s))
{ //当 [i, j-1] 的长度大于 [i+1, j] 的长度,或者二者长度相等并且
//[i, j-1] 的字典序小于 [i+1, j] 的字典序,则选择 [i, j-1],否则选择后者
dp[i][j].len = dp[i][j-1].len;
dp[i][j].s = dp[i][j-1].s;
}
else
{
dp[i][j].len = dp[i+1][j].len;
dp[i][j].s = dp[i+1][j].s;
}
}
}
}
cout<<dp[1][len].s<<endl;
}
return 0;
}
</span>
UVa11404Palindromic Subsequence(最大回文串,区间DP)
原文地址:http://blog.csdn.net/u014028317/article/details/45366657