Dynamic Programming (DP), compressed state, inserting characters to form palindrome strings

Source: Internet
Author: User

Title Link: http://poj.org/problem?id=1159

Problem Solving Report:

1. The state transfer equation of LCS is

if (Str[i-1]==str[j-1]) Dp[i][j]=dp[i-1][j-1]+1;else Dp[i][j]=max (dp[i-1][j],dp[i][j-1]);

2, because can not open dp[5005][5005], so consider the compression state

Using the rolling array method, the state transfer equation of LCS can be rewritten as

if (str1[i-1]==str2[j-1]) {    dp[i%2][j]=dp[(i-1)%2][j- 1] +1;} Else dp[i%2][j]=max (dp[(-1)%2][j],dp[i%2][j-1 ]);
    • Source Code
#include <stdio.h> #include <algorithm> #include <string.h> #include <iostream> #define MAX 5005using namespace Std;///lcs state transfer equation, D[i][j]=max (d[i-1][j],d[i][j-1]),///lcs of the state transfer equation in the form of a rolling array, D[i%2][j]=max (d[(i-1 )%2][j],d[i%2][j-1]) int dp[2][max];///Scroll array int main () {    char Str1[max],str2[max];    int n;    cin>>n;    cin>>str1;    for (int i=0; i<n; i++)        str2[n-i-1]=str1[i];    Memset (Dp,0,sizeof (DP));    for (int i=1, i<=n; i++)    {for        (int j=1; j<=n; J + +) {            if (str1[i-1]==str2[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;}

  

  

Dynamic Programming (DP), compressed state, inserting characters to form palindrome strings

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.