zoukankan      html  css  js  c++  java
  • poj 1159 (最长公共子序列)

    求一个串需要添加多少个字符才能变成回文。

    思路: 求出这个串与他的反串的最大公共子序列, 其实这个序列就是最大的已存在的回文数。 然后用总的数量减之即可

    Palindrome
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 45849   Accepted: 15630

    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

    Source

     用滚动数组比较好.

    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    using namespace std;
    #define N 5050
    
    char g[N],g1[N];
    int dp[2][N];
    
    int main()
    {
        int n;
        scanf("%d",&n);
        scanf("%s",g+1);
        int cnt=0;
        for(int i=n;i>=1;i--)
        {
            g1[i]=g[++cnt];
        }
        int a=0,b=1;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                if(g[i] == g1[j])
                {
                    dp[b][j]=dp[a][j-1]+1;
                }
                else dp[b][j]=max(dp[b][j-1],dp[a][j]);
            }
            swap(a,b);
        }
        printf("%d\n",n-max(dp[0][n],dp[1][n]));
        return 0;
    }
  • 相关阅读:
    pymysql 防止sql注入案例
    4、【常见算法】一道经典的额递归题目
    3、【常见算法】寻找非递减序列中绝对值最小值的绝对值
    2、【常见算法】按序重排问题
    9、【排序算法】基数排序
    8、【排序算法】桶排序
    7、【排序算法】归并排序
    6、【排序算法】堆排序
    20、【图】Prim(普里姆)算法
    19、【图】Kruskal(克鲁斯卡尔)算法
  • 原文地址:https://www.cnblogs.com/chenhuan001/p/2979355.html
Copyright © 2011-2022 走看看