zoukankan      html  css  js  c++  java
  • 线性DP POJ 1159 Palindrome

    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 }
  • 相关阅读:
    CodeForces 408E Curious Array(组合数学+差分)
    CodeForces 519E A and B and Lecture Rooms(倍增)
    洛谷 4051 [JSOI2007]字符加密(后缀数组)
    哇,两门学考都是A(〃'▽'〃)
    BZOJ 1977 严格次小生成树
    XJOI 3606 最大子矩形面积/LightOJ 1083 Histogram(单调栈/笛卡尔树)
    XJOI 3629 非严格次小生成树(pqq的礼物)
    XJOI 3363 树4/ Codeforces 739B Alyona and a tree(树上差分+路径倍增)
    [转载]别让用户发呆—设计中的防呆策略
    Linux下的链接文件
  • 原文地址:https://www.cnblogs.com/c1299401227/p/5495845.html
Copyright © 2011-2022 走看看