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;
            }
    
    
    
  • 相关阅读:
    巧妙使用df和du查看文件和目录的内存占用
    简谈
    SELECT语句的常用方法
    MySQL的安装和基本操作
    数据库 --- 索引
    数据库 --- Group by的使用心得
    数据库面试题 --- 谈谈你对视图的理解
    蚁群算法matlab源码
    职场人每天早晨做一个动作轻松提升工作效率
    职场新人请教问题一定不能犯的两个错误
  • 原文地址:https://www.cnblogs.com/chenchunhui/p/4732581.html
Copyright © 2011-2022 走看看