专题测试三 贪心与动态规划 H - Palindromic Subsequence

  1. 题目
    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
  2. 思路
    寻找不连续的回文字符串,dp[i][j]表示从i到j的最长回文串字符数,str表示字符串,如果s[i]==s[j],就在两端加上这个字符,否则取dp[i+1][j]和dp[i][j-1]中字符串最长、字典序最小的。
  3. 代码
    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    int dp[1050][1050];
    string str[1050][1050];
    
    char s[1050];
    int n,i,j,k,p;
    
    int main()
    {
        while(scanf("%s",s+1)!=EOF)
        {
    		n=strlen(s+1);
            for(i=1;i<=n;i++)
            {
                dp[i][i]=1;
                str[i][i]=s[i];
            }
            for(k=1;k<=n;k++)
    			for(i=1;i+k<=n;i++)
    			{
    				j=i+k;
    				dp[i][j]=max(dp[i+1][j], dp[i][j-1]);
    				if(s[i] == s[j])
    				{
    					dp[i][j]=max(dp[i][j],dp[i+1][j-1]+2);
    					str[i][j]=s[i]+str[i+1][j-1]+s[j];
    				}
    				else if(dp[i+1][j] == dp[i][j-1])
    					str[i][j]=min(str[i+1][j],str[i][j-1]);
    				else if(dp[i][j]   == dp[i+1][j])
    					str[i][j]=str[i+1][j];
    				else if(dp[i][j]   == dp[i][j-1])
    					str[i][j]=str[i][j-1];
               }
    		cout<<str[1][n]<<endl;
        }
    }
posted @ 2022-02-17 12:27  Benincasa  阅读(21)  评论(0编辑  收藏  举报