Blue Bridge Cup palindrome string LCS

If a string is read from left to right and right to left reading are the same, then the string is a palindrome string. For "abcba"example: "abccba", .

Garlic Jun want to add character to become a non-palindromic string palindrome string. For example: "trit"You can add a 'i'becomes palindromic sequence "tirit". Please work with a program that, for a given string, you need to add at least a few characters, to become a palindrome string.

Input Format

Enter a length of  n (1 \ leq n \ leq 3000)n- ( . 1 n- . 3 0 0 0 )  of the string. (String contains only letters)

Output Format

Output requires a minimum number of characters to add, per line.

Sample input

trit

Sample Output

1

After the inverted palindromic sequence string, the string is the same as the original.

So we just put a given string reversing the order of the original string seeking the longest common subsequence, then the total length of the string minus the number of characters the length of the longest common subsequence is the difference, that is the answer.

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char a[3010];
char b[3010];
int lcs[3010][3010];


int main()
{
    memset(lcs,0,sizeof(lcs));
   char x ;
   int k=1;


   while(scanf("%c",&x)==1&&x!=10)
   {
      a[k++]=x;
   }
   for(int i=1 ;i<k+1;i++)
   {
       b[i]=a[k-i];
   }
   for(int i=1 ;i<k+1;i++)
    for(int j=1;j<k+1;j++)
   {
       if(a[i]==b[j])
        lcs[i][j]=lcs[i-1][j-1]+1;
       else
        lcs[i][j]=max(lcs[i-1][j],lcs[i][j-1]);
   }
    int sum = k-lcs[k][k];
    printf("%d",sum);


    return 0;
}


Published 19 original articles · won praise 8 · views 4144

Guess you like

Origin blog.csdn.net/paohui001lqp/article/details/79767573