UVA 11404 Palindromic Subsequence (去除字符DP,4级)
E - Palindromic Subsequence
Crawling in process...
Crawling failed
Time Limit:3000MS
Memory Limit:0KB 64bit IO Format:%lld & %llu
Appoint description:
Description
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
去除
去除最少的字符使其是回文串,字典序最小。直接记录每次最优更新用string
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) using namespace std; const int mm=1005; char s[mm],rs[mm]; class Node { public: int len;string s; bool operator<(const Node&x)const { if(len!=x.len)return len<x.len; return s>x.s; } }dp[mm][mm]; void LCS(int len) { FOR(i,0,len) { dp[i][0].len=0;dp[i][0].s.clear(); dp[0][i].len=0;dp[0][i].s.clear(); } FOR(i,1,len)FOR(j,1,len) { if(s[i]==rs[j])//lcs { dp[i][j].len=dp[i-1][j-1].len+1; dp[i][j].s=dp[i-1][j-1].s+s[i]; } else { dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } string revrse(string s) { string tmp=""; for(int i=s.length()-1;i>=0;--i) tmp+=s[i]; return tmp; } string getans(int len) { Node ans; ans.s.clear();ans.len=0; FOR(i,1,len-1) { ans=max(ans,dp[i][len-i]); } ans.len+=ans.len; ans.s+=revrse(ans.s); Node tmp; FOR(i,1,len) { tmp.len=2*dp[i-1][len-i].len+1; tmp.s=dp[i-1][len-i].s+s[i]+revrse(dp[i-1][len-i].s); ans=max(ans,tmp); } return ans.s; } int main() { while(cin>>s+1) {int len=strlen(s+1); FOR(i,1,len)rs[i]=s[len-i+1]; LCS(len); cout<<getans(len)<<"\n"; } return 0; }
The article write by nealgavin