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 ;

    }

  • 相关阅读:
    猴子选大王(约瑟夫环)
    centos 安装thrift
    KMP字符串匹配算法
    会话技术整理
    PHP数组整理版
    PHP基础知识6【系统内置函数--数组】
    PHP基础知识5【系统内置函数--字符串】
    PHP基础知识笔记4
    PHP基础知识笔记3
    PHP基础知识笔记2
  • 原文地址:https://www.cnblogs.com/xiaolongchase/p/2135532.html
Copyright © 2011-2022 走看看