POJ1159

题目内容
Palindrome
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 39600 Accepted: 13434

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
IOI 2000



动规,找出当前字符串和它的逆字符串的最长公共子序列,输出其与字符串长度之差即可。

 1 #include<cstdio>
2 #include<cstring>
3 #define MAX 5010
4 char str1[MAX],str2[MAX];
5 long maxlen[2][MAX];
6 long max(long a,long b)
7 {
8 return a>b?a:b;
9 }
10 int main(void)
11 {
12 long n,i,j;
13 scanf("%ld",&n);
14 scanf("%s",str1);
15 for(i=n;i!=0;i--)
16 str1[i]=str1[i-1];
17 str1[0]=0;
18 str1[n+1]=0;
19 for(i=1;i<=n;i++)
20 str2[i]=str1[n-i+1];
21 str2[n+1]=0;
22 /*debug
23 for(i=1;i<=n;i++)
24 printf("%c",str1[i]);
25 printf("\n");
26 for(i=1;i<=n;i++)
27 printf("%c",str2[i]);
28 printf("\n");
29 */
30 memset(maxlen,0,sizeof(maxlen));
31 long e=0;
32 for(i=1;i<=n;i++)
33 {
34 e=1-e;
35 for(j=1;j<=n;j++)
36 {
37 if(str1[i]==str2[j])
38 maxlen[e][j]=maxlen[1-e][j-1]+1;
39 else
40 maxlen[e][j]=max(maxlen[e][j-1],maxlen[1-e][j]);
41 }
42 }
43 printf("%ld\n",n-maxlen[e][n]);
44 return 0;
45 }



posted on 2011-11-05 17:27  SilVeRyELF  阅读(127)  评论(0编辑  收藏  举报

导航