HDU 1513 && POJ 1159 palindrome (dp+lcs+ scrolling array)

Source: Internet
Author: User

Test instructions: Given a string that lets you turn it into a palindrome, add a minimum number of characters.

Analysis: Dynamic planning is very obvious, is not the current thinking, or ask others just know, oh, originally either write, since it is palindrome string,

So the final pros and cons have to be the same, so we have to ask for LCS, so that the public to find out, then use the total minus this LCS,

Then the rest is definitely not paired, it must be added.

Thought has, here again a problem, this request LCS, to use the space complexity is too big, mle ... With the idea, still can't live,

This problem should be done with a scrolling array, I think in the case of LCS, the first dimension we only used i-1 and I, so, we can only open 2 lines in the second dimension is enough,

Constantly back and forth storage, the first row and the second line repeatedly, so OK, so this problem is resolved.

The code is as follows:

#include <iostream> #include <cstdio> #include <cstring> #include <cmath>using namespace std; const int MAXN = 10;int D[2][maxn];char S[MAXN], T[maxn];int main () {    int n;    while (~SCANF ("%d", &n)) {        scanf ("%s", s+1);        for (int i = 1; I <= n; ++i)            t[i] = s[n-i+1];        T[n+1] = ' + ';        memset (d, 0, sizeof (d));        for (int i = 1, i <= N; ++i) for            (int j = 1; j <= N; ++j) {                int x = i% 2;                int y = 1-x;                if (s[i] = = T[j])  d[x][j] = d[y][j-1] + 1;                else  d[x][j] = max (D[y][j], d[x][j-1]);            }        printf ("%d\n", N-d[n%2][n]);    }    return 0;}

HDU 1513 && POJ 1159 palindrome (dp+lcs+ scrolling array)

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.