zoukankan      html  css  js  c++  java
  • 动态规划——G 回文串

    G - 回文串
    Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
    Submit Status

    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
    题目大意:一串字符,从左往右读和从右往左读是完全一样的。
    解题思路:
    这个题目可以转化为求最长公共子串的问题,就是将原字符串逆转,然后求原字符串和逆转字符串的最长公公子串,最后要注意c数组要定义成short型,否则会超内存

    程序代码:
     1 #include<cstdio>
     2 #include <cstring>
     3 using namespace std;
     4 #define MAX 5010
     5 char a[MAX],b[MAX];
     6 short c[MAX][MAX];
     7 int max(int x,int y)
     8 {
     9     return x>y?x:y;
    10 }
    11 int main()
    12 {
    13     int n;
    14     scanf("%d",&n);
    15     scanf("%s",a);
    16     for(int i=n-1;i>=0;i--)
    17         b[n-i-1]=a[i];
    18         b[n]='';
    19     memset(c,0,sizeof(c));
    20     for(int i=0;i<n;i++)
    21         for(int j=0;j<n;j++)
    22     {
    23         if(a[i]==b[j])
    24             c[i+1][j+1]=c[i][j]+1;
    25         else
    26             {
    27                 if(c[i+1][j]>c[i][j+1])
    28                     c[i+1][j+1]=c[i+1][j];
    29                 else  c[i+1][j+1]=c[i][j+1];
    30             }
    31     }
    32     printf("%d
    ",n-c[n][n]);
    33 
    34 return 0;
    35 }
    View Code
    版权声明:此代码归属博主, 请务侵权!
  • 相关阅读:
    atitit.颜色查找 根据范围 图像处理 inRange
    Atitit 跨平台的系统截图解决方案
    Atitit java opencv 捕获视频
    路法Atiti
    Atitit 获取本机图像设备视频设备列表 设备检索列表解决方案
    Atitit 团队工具链体系打造提升团队效率的一些通用软件 attilax总结
    Atitit gui控件定位解决方案
    Atitit html5.1 新特性attilax总结
    Atitti 模板匹配 List matchTemplate(
    利用CRebar和CDialogBar编写可浮动的dialog类型的工具栏
  • 原文地址:https://www.cnblogs.com/www-cnxcy-com/p/4722076.html
Copyright © 2011-2022 走看看