Poj 1159 palindrome (string-to-text: LCs)

Source: Internet
Author: User

Poj 1159 palindrome (string-to-text: LCs)

Http://poj.org/problem? Id = 1159

Question:

I will give you a string and ask you if you need to insert a few characters into the string, but it will become a return string.

Analysis:

First, match the original string with its inverse string to find the longest common subsequence. the string of the longest common subsequence must be a return string. therefore, the rest of the original string does not constitute a background. we only need to add the remaining part of the characters to the corresponding position, and the original string naturally becomes a background.

So the answer to this question is: N minus (the LCS length of the original string and the inverse string ).

For example, DP [I] [J] = X indicates the longest common subsequence of the first I character of string a and the first J character of string B.

Initialization: DP is all 0.

Status transfer:

A [I] = B [J]: DP [I] [J] = DP [I-1] [J-1] + 1.

A [I]! = B [J]: DP [I] [J] = max (DP [I-1] [J], DP [I] [J-1]).

Final requirement: DP [N] [M].

The two-dimensional rolling array used by the program. If int [5000] [5000] is used, the memory will be exceeded.

AC code:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=5000+5;int n;char s1[maxn],s2[maxn];int dp[2][maxn];int main(){    while(scanf("%d",&n)==1)    {        scanf("%s",s1);        for(int i=0;i<n;i++)            s2[i]=s1[n-1-i];        memset(dp,0,sizeof(dp));        for(int i=1;i<=n;i++)        for(int j=1;j<=n;j++)        {            if(s1[i-1]==s2[j-1])                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]);        }        printf("%d\n",n-dp[n%2][n]);    }    return 0;}

Poj 1159 palindrome (string-to-text: LCs)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.