zoukankan      html  css  js  c++  java
  • 2015 HUAS Summer Trainning #5~G

    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
    解题思路:这是一个回文串问题,题目的意思是输入一个字符串,求出将其变成一个回文串需要插入字符的最少数。可以用动态规划法,使用dp用状态转移方程。
    程序代码:
      #include<iostream>
      #include<stdio.h>
      #include<string.h>
      using namespace std;
      short dp[5005][5005];
      char a[5005];
      char b[5005];
      int main(){
          int n,i,j;
         while(scanf("%d",&n)!=EOF){       
            scanf("%s",a+1);
            strcpy(b,a+1);
            for( i=0;i<=n;i++){
                      dp[i][n]=0;
                      }
            for( j=0;j<=n;j++){
                      dp[0][j]=0;
                      }
            for( i=1;i<=n;i++){           
                 for( j=n-1;j>=0;j--){
                              if(a[i]==b[j]){
                                 dp[i][j]=dp[i-1][j+1]+1;
                                 }
                              else{
                                 dp[i][j]=((dp[i-1][j])>(dp[i][j+1]))?(dp[i-1][j]):(dp[i][j+1]);
                                 }
                                 }
                                 }
            int res=n-dp[n][0];
            printf("%d
    ",res);
              }
            return 0;
            }
    
    
    
  • 相关阅读:
    MySQL数据库 : 高级查询
    ElasticSearch : High Rest Api 使用
    Java : JavaWeb和Tomcat相关
    Linux : Ubuntu 安装 RabbitMQ
    Spring : Spring Security
    Java : logback简单配置
    Spring : JPA的单独使用
    Java : Netty 入门案例
    python__PIP : 安装第三方库
    好文章收藏(持续更新)
  • 原文地址:https://www.cnblogs.com/chenchunhui/p/4732581.html
Copyright © 2011-2022 走看看