Uva11151longest palindrome (recurrence)

Source: Internet
Author: User

Question; uva11151longest palindrome (recurrence)


A string that can be obtained by removing some characters.


Solution: DP [I] [J] represents the maximum length of the return from string I bit to J bit.

If s [I] = s [J], DP [I] [J] = DP [I-1] [J-1] + 2, because the head and tail are the same, if the longest text return from I to J is required, only 2 is required for the longest text return in the middle.

Otherwise, DP [I] [J] = max (DP [I] [J-1], DP [I + 1] [J ]);

Computing sequence: fixed length is calculated each time, and the length ranges from small to large. Note: Empty strings.


Code:

#include <cstdio>#include <cstring>const int N = 1005;int dp[N][N];char str[N];void init (int len) {for (int i = 0; i < len; i++) {dp[i][i] = 1;if (i + 1 < len) {if (str[i] == str[i + 1])dp[i][i + 1] = 2;elsedp[i][i + 1] = 1;}}}int Max (const int a, const int b) { return a > b ? a: b; }int main () {int cas;int len;scanf ("%d%*c", &cas);while (cas--) {gets(str);len = strlen (str);if (!len) {printf ("0\n");continue;}init (len);for (int n = 3; n <= len; n++) {for (int i = 0, j = n - 1; j < len; i++, j++) {if (str[i] == str[j])dp[i][j] = dp[i + 1][j - 1] + 2;else dp[i][j] = Max (dp[i + 1][j], dp[i][j - 1]); }}printf ("%d\n", dp[0][len - 1]);}return 0;}


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.