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;
    }
     
  • 相关阅读:
    设计模式总结
    字符编码小结
    搞定java.io
    将代码托管到GitHub上
    linuxlinux 路由表设置 之 route 指令详解 路由表设置 之 route 指令详解
    linux子系统的初始化_subsys_initcall()
    Linux系统目录结构介绍
    EtherType :以太网类型字段及值
    socket编程原理
    linux下的网络接口和网络桥接
  • 原文地址:https://www.cnblogs.com/fht-litost/p/8855340.html
Copyright © 2011-2022 走看看