hdoj 1513 Palindrome 【LCS 滚动数组实现】

Palindrome

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4062    Accepted Submission(s): 1384


Problem Description
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个字符组成的字符串,问最少增加几个字符是它成为回文字符串。

思路:反转原字符串a为b,求a字符串和b字符串的LCS。用N减去即可。

由于N太大,开不了5000*5000的数组。多亏队友给我讲了滚动数组实现LCS。。。好巧妙


由于当前状态dp[ i ][ j ] 只与上一个状态有关,所以对于状态转移方程
一:a[ i ] == b[ j ]时
dp[ i ][ j ] = dp[ i-1 ] [ j-1 ] + 1 可变为dp[ i%2 ][ j ] = dp[ (i-1)%2 ][ j-1 ] + 1。

二:a[ i ] != b[ j ]时,
dp[ i ][ j ] = max(dp[ i-1 ][ j ], dp[ i ][ j-1 ])可变为dp[ i%2 ][ j ] = max(dp[ (i-1)%2 ][ j ], dp[ i%2 ][ j-1 ])。


AC代码:

#include 
#include 
#include 
#define MAXN 5000+10
using namespace std;
char a[MAXN], b[MAXN];
int dp[2][MAXN];
int N;
int main()
{
    while(scanf("%d", &N) != EOF)
    {
        scanf("%s", a);
        strcpy(b, a);
        strrev(b);
        int len = strlen(a);
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= len; i++)
        {
            for(int j = 1; j <= len; 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", len - max(dp[0][len], dp[1][len]));
    }
    return 0;
}


你可能感兴趣的:(DP之LCS)