Skip to content

T01159: Palindrome

dp, http://cs101.openjudge.cn/practice/01159/

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.

输入

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.

输出

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

样例输入

5
Ab3bd

样例输出

2

来源

IOI 2000

【陈子良 25物理学院】动态规划,设dp[i][d]表示对字符串中从索引i开始,长度为d的子串,将其变为回文串所需添加的字符数。如果s[i]==s[i+d],那么只要把里面的子串变成回文串即可,dp[i][d]=dp[i+1][d-1]。如果s[i]!=s[i+d],我们要么把s[i:i+d]变成回文串,再在左边加上s[i+d],要么把s[i+1:i+d+1]变成回文串,再在右边加上s[i]。这里把d方向维度变成了滚动数组。

python
N=int(input())
s=input()
if N==1:
    print(0)
    exit()
dp1=[0]*N
dp2=[0]*(N-1)
for i in range(N-1):
    if s[i]==s[i+1]:
        dp2[i]=0
    else:
        dp2[i]=1
for d in range(2,N):
    dp3=[0]*(N-d)
    for i in range(N-d):
        if s[i]==s[i+d]:
            dp3[i]=dp1[i+1]
        else:
            dp3[i]=min(dp2[i],dp2[i+1])+1
    dp1=dp2[:]
    dp2=dp3[:]
print(dp2[0])