zoukankan      html  css  js  c++  java
  • poj 1159 回文词

    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

    5Ab3bd

    Sample Output

    2

    题意:

        输入一串字符,计算插入几次字符可以使其变为回文字符串(类似'3210123'),求出最少的次数。

    输入:

        字符串长度,字符串。

    输出:

        最少的操作次数。

        

         此题的状态为始末位置,要想知道min[start][end]的值,就要判断s[start],s[end]是否相同。若相同,则 min[start[end]=min[start+1][end-1]。若不同,则取min[start+1][end]和min[start] [end-1]中的小值再++。那么问题就转化成了求min[start+1][end]和min[start][end-1]的值的子问题。以此类推, 直到求出所有情况下的最小值,递归依次返回各值,最后得到min[start][end]。

    代码:

    #include<iostream>

    #include<memory.h>

    using namespace std ;

    char a[5001] ;

    int x[5001][5001] ;

    int find(int i, int j){

    if(i>j) return 0 ; //递归结束

    if(x[j]>0) return x[j] ; //已经计算过

    if(a==a[j]){ //字符相同,起始位置进一,末位置退一

    x[j-1] = find(i+1, j-1) ;

    return x[j-1] ;

    }

    if(a!=a[j]){

    x[j] = find(i+1, j) ; //起始位置进一

    x[j-1] = find(i, j-1) ; //末位置退一

    if(x[j]>x[j-1])

    return x[j-1] + 1 ;

    else

    return x[j] + 1 ;

    }

    return 0 ;

    }

    int main(){

    int n ;

    memset(x, 0, 5001) ;

    cin >> n ;

    cin >> a ;

    cout << find(0, n-1) << endl ;

    return 0 ;

    }

  • 相关阅读:
    Linux 下面安装 nginx 以及进行TCP反向代理、负载均衡的过程
    AMD全新32核线程撕裂者GeekBench跑分曝光:超2950X近一倍
    Win7 & VS2013 编译 WebKit 总结
    窗宽窗位与其处理方法
    编写Delphi控件属性Stored和Default的理解及应用
    vSphere、Hyper-V与XenServer 你选哪个?
    写给那些常年战痘的痘友们~~~
    怎么解决xp系统不能安装NET Framework4.0?
    Kali Linux渗透基础知识整理(四):维持访问
    解决vista和win7在windows服务中交互桌面权限问题:穿透Session 0 隔离
  • 原文地址:https://www.cnblogs.com/xiaolongchase/p/2135532.html
Copyright © 2011-2022 走看看