1. 程式人生 > 其它 >專題測試三 貪心與動態規劃 H - Palindromic Subsequence

專題測試三 貪心與動態規劃 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;
        }
    }