码迷,mamicode.com
首页 > 其他好文 > 详细

线性DP POJ 1159 Palindrome

时间:2016-05-15 19:44:02      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

Palindrome
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 59101   Accepted: 20532

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
 1 /* 判断最少添加的字符数目,这个用for顺序太难写了,我就用记忆化搜索,因为这个题目内存是65MB,5000*5000会超过限制,short int在数据不超的情况下,可以节约空间,sizeof(int)=4,而sizeof(short)=2
 2    DP方程:if(s[i]==s[j])f[i][j]=f[i+1][j-1]
 3            else f[i][j]=min(f[i+1][j],f[i][j-1])+1;
 4            其中f[i][j]表示i--j这个区间形成回文串的最少添加字符数目 
 5 */
 6 #include<iostream>
 7 using namespace std;
 8 #include<cstdio>
 9 #include<cstring>
10 #define N 5003
11 short f[N][N]={0};
12 char s[N];
13 int n;
14 int search(int l,int r)
15 {
16     if(f[l][r])return f[l][r]; 
17     if(l==r-1)
18     {
19         if(s[l]==s[r]) return f[l][r]=0;
20         return f[l][r]=1;
21     }
22     if(l==r)
23       return f[l][r]=0;
24     if(s[l]==s[r])
25       return f[l][r]=search(l+1,r-1);
26     else 
27     {
28         return f[l][r]=min(search(l+1,r),search(l,r-1))+1;
29     }
30 }
31 int main()
32 {
33     scanf("%d%s",&n,s+1);
34     cout<<search(1,n)<<endl;
35     return 0;
36 }

 

线性DP POJ 1159 Palindrome

标签:

原文地址:http://www.cnblogs.com/c1299401227/p/5495845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!