Palindrome-最长公共子序列

C - Palindrome
Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit  Status  Practice  POJ 1159

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
此题的真正用途是求字符串反转后与他本身之间最大公共子序列
(至于为什么是求公共子序列,因为对于一个有序的字符串,如果有些字符已经帮你匹配好了对应的字符,那么相应的操作就会减少)
(因此,将符合条件的有序的字符去掉,剩下的便是没有匹配成功需要插入字符才能一一匹配)
问题在于要缩小数组的大小,从二维变为一维,所以
写出一维的转移方程非常重要,代码中介绍
/*
Author: 2486
Memory: 736 KB		Time: 1032 MS
Language: G++		Result: Accepted
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=5000+5;
int dp[maxn];
string ss,kk;
int n;
int main() {
    while(~scanf("%d",&n)) {
        cin>>ss;
        kk=ss;
        reverse(kk.begin(),kk.end());
        memset(dp,0,sizeof(dp));
        int l,maxp;
        for(int i=0; i<n; i++) {
            maxp=0;
            for(int j=0; j<n; j++) {
                l=dp[j];
                if(ss[i]==kk[j]&&dp[j]<maxp+1)dp[j]=maxp+1;
                maxp=max(maxp,l);
            }
        }
        int ans=0;
        for(int i=0;i<n;i++){
            ans=max(ans,dp[i]);
        }
        printf("%d\n",n-ans);
    }
    return 0;
}


你可能感兴趣的:(Palindrome-最长公共子序列)