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 }
  • 相关阅读:
    Django之模板系统
    Django之ORM操作
    Django之路由分配系统
    基于模态对话框 学生管理系统
    初识Django
    ORM框架之SQLALchemy
    MySQL查询性能调优化
    MySQL练习题
    MySQL自带功能介绍
    javascript时间戳和日期字符串相互转换
  • 原文地址:https://www.cnblogs.com/c1299401227/p/5495845.html
Copyright © 2011-2022 走看看