Palindromic Subsequence
64-bit integer IO format: %lld Java class name: Main
Palindromic Subsequence
Palindromic Subsequence |
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
- Maximum length of string is 1000.
- Each string has characters `a' to `z' only.
Input
Input consists of several strings, each in a separate line. Input is terminated by EOF.
Output
For each line in the input, print the output in a single line.
Sample Input
aabbaabb computer abzla samhita
Sample Output
aabbaa c aba aha
题意:给定一个字符串,求出去掉某些字符后的最长回文串,如果长度相同则输出字典序最小的回文串。
思路:原串翻转后和原串的最长公共子序列就是最长回文串。状态转移时可以处理字典序最小问题。,这样转移也会导致得到的公共序列并不一定就是回文串,但是可以保证前半部分公共序列一定是回文串的前半部分,所以输出结果的时候注意根据公共序列长度的奇偶选择重复两次输出前半部分就好。
例如: kfclbckibbibjccbej
原串和反串得到的公共序列却是bcibbibc
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 50007;
const int inf = 0x3f3f3f3f;
const int mod = 10007;
char str[1100], str1[1100];
struct node
{
int len;
string s;
} dp[1007][1007];
int main()
{
while(scanf("%s",str)!=EOF)
{
int len=strlen(str);
strcpy(str1,str);
reverse(str1,str1+len);
for(int i=0; i<=len; i++) dp[0][i].len=0,dp[0][i].s="";
for(int i=1; i<=len; i++)
{
for(int j=1; j<=len; j++)
{
if(str[i-1]==str1[j-1]) dp[i][j].len=dp[i-1][j-1].len+1,dp[i][j].s=dp[i-1][j-1].s+str[i-1];
else if(dp[i-1][j].len<dp[i][j-1].len) dp[i][j].len=dp[i][j-1].len,dp[i][j].s=dp[i][j-1].s;
else if(dp[i-1][j].len>dp[i][j-1].len) dp[i][j].len=dp[i-1][j].len,dp[i][j].s=dp[i-1][j].s;
else dp[i][j].len=dp[i-1][j].len,dp[i][j].s=min(dp[i-1][j].s,dp[i][j-1].s);
}
}
string ans = dp[len][len].s;
int l=dp[len][len].len;
if(l&1)
{
for(int i=0;i<=l/2;i++)cout<<ans[i];
for(int i=l/2-1;i>=0;i--) cout<<ans[i];
cout<<endl;
}
else
{
for(int i=0;i<l/2;i++)cout<<ans[i];
for(int i=l/2-1;i>=0;i--) cout<<ans[i];
cout<<endl;
}
}
return 0;
}