Palindrome
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 Source |
【题意】加入最少的字符使字符串左右对称
【思路】dp[i][j]表示使第i位到第j位的字符串对称所需的最小字符数
状态转移方程:
dp[i][j]=dp[i+1][j-1] ch[i]==ch[j]
dp[i][j]=max(dp[i+1][j]+1,dp[i][j-1]+1) ch[i]!=ch[j];
此题不难,但是直接开dp[5000][5000]会超内存,就用滚动数组,这个滚动数组有三个,有点少见。。
【代码】
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int dp[5010][3];
char ch[5010];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
scanf("%s",ch+1);
memset(dp,0,sizeof(dp));
int e=0;
for(int len=2;len<=n;len++)
{
e=(e+1)%3;//对3取余
for(int i=1;i<=n;i++)
{
int j=i+len-1;
if(j>n)break;
if(ch[i]==ch[j])
{
if(i+1<=j-1)dp[i][e]=dp[i+1][(e+1)%3];
else dp[i][e]=0;
}
else
{
dp[i][e]=min(dp[i][(e+2)%3]+1,dp[i+1][(e+2)%3]+1);
}
}
}
printf("%d\n",dp[1][e]);
}
return 0;
}