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;
            }
    
    
    
  • 相关阅读:
    组建小型局域网
    如何解决无法登陆微软账号
    常用网页收录入口
    Google正确搜索方法
    电脑无法识别U盘(usb类外接设备)的解决办法
    如何生成一副Poker
    Camtasia Studio8使用教程
    windows蓝屏代码大全及常见蓝屏解决方案
    [bzoj3712][PA2014]Fiolki
    [NOI2018]归程
  • 原文地址:https://www.cnblogs.com/chenchunhui/p/4732581.html
Copyright © 2011-2022 走看看