Palindrome(三部曲一)

来源:互联网 发布:大学生怎么做淘宝店铺 编辑:程序博客网 时间:2024/05/10 20:38
Palindrome
Time Limit : 6000/3000ms (Java/Other) Memory Limit : 131072/65536K(Java/Other)

Problem Description
A palindrome is a symmetrical string, that is, a string readidentically from left to right as well as from right to left. Youare to write a program which, given a string, determines theminimal number of characters to be inserted into the string inorder to obtain a palindrome.

As an example, by inserting 2 characters, the string "Ab3bd" can betransformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However,inserting fewer than 2 characters does not produce apalindrome.


Input
Your program is to read from standard input. The first linecontains one integer: the length of the input string N, 3<= N <= 5000. The second linecontains one string with length N. The string is formed fromuppercase letters from 'A' to 'Z', lowercase letters from 'a' to'z' and digits from '0' to '9'. Uppercase and lowercase letters areto be considered distinct.


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


Sample Input
5
Ab3bd


Sample Output
2


Source

PKU

用动态规划完成的,先是超时,后是超内存。最后原因找到后竟很可笑,C的代码用C++交的。

#include<stdio.h>
char a[5010];
int n;
int k[5010][5010]={0};
int palindrome (int t,int s)
{
if(t>s )
return 0;
if(k[t][s]>0)
return k[t][s];
if(a[t]==a[s])
{
k[t+1][s-1]=palindrome(t+1,s-1);
return k[t+1][s-1];
}
if(a[t]!=a[s])
{
k[t+1][s]=palindrome(t+1,s);
k[t][s-1]=palindrome(t,s-1);
if(k[t+1][s]>k[t][s-1])
return k[t][s-1]+1;
else
return k[t+1][s]+1;
}
return 0;
}
int main()
{
scanf("%d",&n);
scanf("%s",a);
printf("%d\n",palindrome(0,n-1));
return 0;
}

原创粉丝点击