uva 11404 Palindromic Subsequence(LCS 记录中间过程)@

Palindromic Subsequence

3000ms
131072KB
This problem will be judged on UVA. Original ID:  11404
64-bit integer IO format:  %lld      Java class name:  Main
Font Size:   

[PDF Link]


  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;
}













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值