zoukankan      html  css  js  c++  java
  • POJ 1159 Palindrome

    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

    题意
    给出一定长度的一个字符串,问最少添加多少个字符才能使其成为回文串。

    分析
    回文串即为从左读和从右读都是一样的串。因此,我们对比一下正串和逆串,找出LCS,这就是能构成回文串的部分。
    那么剩下的部分就是无法形成回文串,于是我们最少需要再次添加这部分串。答案即为 n-LCS。
    另外,这道题限制内存。为了节省空间,计算LCS时只用保存前一个状态的值。
    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<algorithm>
    #include<cstring>
    #include <queue>
    #include <vector>
    #include<bitset>
    #include<map>
    #include<deque>
    using namespace std;
    typedef long long LL;
    const int maxn = 1e4+5;
    const int mod = 77200211+233;
    typedef pair<int,int> pii;
    #define X first
    #define Y second
    #define pb push_back
    //#define mp make_pair
    #define ms(a,b) memset(a,b,sizeof(a))
    const int inf = 0x3f3f3f3f;
    #define lson l,m,2*rt
    #define rson m+1,r,2*rt+1
    typedef long long ll;
    #define N 100010
    
    char a[5050],b[5050];
    int dp[2][5050];
    
    int main(){
        int n;
        scanf("%d",&n);
        scanf("%s",a+1);
    
        for(int i=1;i<=n;i++) b[n-i+1]=a[i];
    
        ms(dp,0);
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(a[i]==b[j]){
                    dp[i%2][j]=dp[(i-1)%2][j-1]+1;
                }else{
                    dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
                }
            }
        }
        cout<<n-dp[n%2][n]<<endl;
        return 0;
    }
     
  • 相关阅读:
    HDU4411 最小费用流
    HDU5934 强连通分量
    一个问题
    SAP模板
    KMP模板
    ]C#中执行SQL文件脚本的代码(非常有用)
    C#调用非托管程序5种方式
    [转]C#中的静态常量(const)和动态常量(static和readonly)用法和区别
    [转]C#开发命名规范总结整理
    [转]关于同步方法里面调用异步方法的探究
  • 原文地址:https://www.cnblogs.com/fht-litost/p/8855340.html
Copyright © 2011-2022 走看看