杭电 1513 Palindrome(LCS)

来源:互联网 发布:多益网络ipo结果 编辑:程序博客网 时间:2024/05/18 03:24
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
5Ab3bd
 

Sample Output
2
 
 
 
刚开始看题目好难,默默地看大神们讨论,偷偷地学会了比较垃圾的滚动数组。
 
#include<stdio.h>#include<string.h>#define max(a,b) (a>b?a:b)char str[5100],arr[5100];int dp[2][5100];//开成5000*5000的肯定超了,这种他们好像叫什么滚蛋数组?哦不对好像是滚动数组 int main(){int m,n,i,j,k,l;while(scanf("%d",&n)!=EOF){memset(dp,0,sizeof(dp));scanf("%s",&str);for(i=0;i<n;i++)arr[i]=str[n-i-1];//把原字符串倒着存一遍,让他们LCS。求出最大子串长度之后剩下的长度就和需要添加的长度一样了 for(i=1;i<=n;i++)for(j=1;j<=n;j++){k=i%2;l=(i-1)%2;//滚动数组的实现,不断地让他们变0,1;真特么方便 if(str[i-1]==arr[j-1]){dp[k][j]=dp[l][j-1]+1;}elsedp[k][j]=max(dp[l][j],dp[k][j-1]);}m=dp[n%2][n];printf("%d\n",n-m);}return 0;}

0 0
原创粉丝点击