Palindrome 动态规划算法 +空间优化

来源:互联网 发布:西瓜趣味编程营 编辑:程序博客网 时间:2024/06/03 22:43


Palindrome

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15   Accepted Submission(s) : 6

Font: Times New Roman | Verdana | Georgia

Font Size:

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

5Ab3bd

Sample Output

2

Source

IOI 2000

/*
dp[i][j]=max(dp[i+1][j-1]+same(i,j),dp[i+1][j],dp[i][j-1])

same(i,j):若str[i]==str[j],则返回1,否则返回0
空间复杂度:O(N^2);
优化:
用数组A[]记录dp[i+1][j-1]、dp[i+1][j];
用数组dp[]记录dp[j]、dp[j-1];
空间复杂度:O(N);
*/
#include<iostream>
#include<malloc.h>
#include<cstdio>
#include<algorithm>

using namespace std;
const int MAXN = 5001;
char str[MAXN];
int dp[MAXN],A[MAXN];
int N;
int maxx(int a, int b){
    if (a<b)
        return b;
    return a;
}
void ss(){
    int i, j;
    memset(dp, 0, sizeof(dp));
 memset(A,0,sizeof(A));
    for (i = N; i > 0; i--){              //注意这里顺序要逆序,否则wa
        for (j = 1; j <= N; j++){
            if (str[i] == str[j]){
                dp[j] = A[j - 1] + 1;
            }
            else{
                dp[j] = maxx(A[j], dp[j - 1]);
            }

        }
        for (j = 1; j <= N; j++){
            A[j] = dp[j];
        }
    }
    cout << N - dp[N] << endl;
}
int main(){
    int i;
    freopen("in.txt", "r", stdin);
    while(~scanf("%d", &N)){
        for (i = 1; i <= N; i++){
            cin >> str[i];
        }
        ss();
    }
    return 0;
}

0 0
原创粉丝点击