B - Palindrome

题目:

A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. 

As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. 

Input

Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.

Output

Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input

5
Ab3bd

Sample Output

2

题意:

给你一串字符,让你添加几个字符,使之变成回文字符串,求出最少的添加字符的个数;

思路:

刚看到这道题时真的是没有思路,然后看了看别人的思路,才知道这道题可以转换成求正反串取最长公共子序列

这是不用变得个数,n-这个值,就是我们要求的最后的结果了;

同时这道题的dp数组不能开成dp[5001][5001],会内存超限,所以要用滚动数组

代码如下:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

//正反串取最長公共子序列

int n;
char a[5001],b[5001];
int dp[2][5001];

int main()
{
    while(~scanf("%d",&n))
    {
        int i,j;
        scanf("%s",a);
        j=0;
        for(i=n-1;i>=0;i--)
        {
            b[j++]=a[i];
        }
        b[j]='\0';
        memset(dp,0,sizeof dp);
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                if(a[i-1]==b[j-1])
                    dp[i%2][j]=dp[(i-1)%2][j-1]+1;
                else
                    dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
            }
        }
        printf("%d\n",n-dp[n%2][n]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/titi2018815/article/details/81361483