Poj1159: palindrome [DP]

Source: Internet
Author: User

Question: How many characters can be added to a string to make it a return string?

Idea: the obvious equation is: DP [I] [J] = min {DP [I + 1] [J], DP [I] [J-1], DP [I + 1] [J-1] (STR [I] = STR [J )}

DP [I] [J] indicates that the characters from I to J are constructed as the characters with the least number of characters added to the input string, but discuss says that this will exceed space + timeout

After observing this equation, the three sub-States are used each time, so the form of the equation is changed as appropriate:

DP [I] [J] indicates the minimum number of characters to be added to a string consisting of substrings whose start length is J, the equation becomes DP [I] [J] = min {DP [I + 1] [J-1], DP [I] [J-1], DP [I + 1] [J-2] (STR [I] = STR [J )}, recursive only need to store the length of J-1 and J-2 data can release the length of J data, using the pointer to change the order of the next three Arrays can be. As a result, the space problem was solved smoothly.

// Poj1159

# Include <cstdio>

# Include <string. h>

# Include <iostream>

Using namespace STD;

Const int maxn = 5009;

Int min (int A, int B)

{

If (A> B) return B; else return;

}

Int main ()

{

Int N;

Char STR [maxn];

Scanf ("% d % s", & N, STR );

Int A [maxn] = {0}, B [maxn] = {0}, C [maxn] = {0 };

Int * ans = A, * f = B, * FF = C, * temp;

For (int K = 1; k <= N; k ++)

{

For (INT I = 1; I <= n-k + 1; I ++)

{

Ans [I] = min (F [I], F [I + 1]) + 1;

If (STR [I-1] = STR [I + K-2]) ans [I] = min (ANS [I], FF [I + 1]);

}

Temp = ff; FF = f; F = ans; ans = temp;

}

Printf ("% d \ n", F [1]);

Return 0;

}

Poj1159: palindrome [DP]

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.