POJ 1159 Palindrome (区间DP)

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

Solution
容易看出,答案即为串S的 |S| - 最长回文子序列长度
用区间DP来求最长回文子序列长度

转移方程:

if(s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2;
else dp[i][j] = max(dp[i+1][j], dp[i][j-1]);

这题卡空间,所以需要滚动区间DP的数组

Code

int n;
char s[maxn];
int dp[2][maxn];
void solve() {
     
    int res = 0;
    dp[0][n] = 1;
    int op = 0;
    for(int i = n-1;i >= 1;--i) {
     
        op ^= 1;
        for(int j = i+1;j <= n;++j) dp[op][j] = dp[op^1][j];
        dp[op][i] = 1;
        for(int j = i+1;j <= n;++j) {
     
            if(s[i] == s[j]) dp[op][j] = dp[op^1][j-1] + 2;
            else dp[op][j] = max(dp[op^1][j],dp[op][j-1]);
            res = max(res,dp[op][j]);
            // debug3(i,j,dp[op][j]);
        }
    } printf("%d\n", n - res);
}
int main() {
     
    scanf("%d",&n);
    scanf("%s",s + 1);
    solve();
    return 0;
}

你可能感兴趣的:(DP)