zoukankan      html  css  js  c++  java
  • poj1159——回文,lcs

    poj1159——回文,lcs

    Palindrome
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 54621   Accepted: 18892

    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
    题意:求给定字符串中插入最少字符使之成为回文,求插入最少字符个数
    思路:所谓回文,就是逆转后还等于原串,因此原串和逆串的lcs剩下的位置即是必须插入的位置,因此本题只需逆转后求lcs,再用n-lcs即可
    dp开二维数组居然MLE了,后来改成short int就AC了,不过又改成滚动数组AC了,滚动数组还是很方便的
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<algorithm>
    
    using namespace std;
    
    const int maxn=5010;
    const int INF=(1<<28);
    int n;
    char s[maxn],t[maxn];
    int dp[2][maxn];
    
    int main()
    {
        while(scanf("%d",&n)!=EOF){
            for(int i=1;i<=n;i++){
                cin>>s[i];
                t[n-i+1]=s[i];
            }
            memset(dp,0,sizeof(dp));
            for(int i=1;i<=n;i++){ /// lcs
                for(int j=1;j<=n;j++){
                    if(s[i]==t[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;
    }
    View Code
    没有AC不了的题,只有不努力的ACMER!
  • 相关阅读:
    子组 正则表达式
    正则表达式
    马云北大演讲完整版:真心话,什么才是阿里的核心竞争力?-2014-03-20
    形象化的spring 依赖注入原理
    程序员的六层境界
    apache配置运行zendframework 2
    php编写简单的页面跳转功能
    php随机验证码
    没啥说的
    PHP流程控制语句下
  • 原文地址:https://www.cnblogs.com/--560/p/4355038.html
Copyright © 2011-2022 走看看