Uva42417-again palindrome (memory-based search)

Source: Internet
Author: User

Title: uva42417-again palindrome)


The following figure shows a string. Given the delete operation, you can delete characters at any position. You can obtain the most input records through this operation.


Solution: DP [I] [J] indicates the maximum number of replies that can be obtained from the delete operation between the I and j characters.

If s [I] = s [J], then DP [I] [J] = DP [I] [J-1] (delete character J) + dp [I + 1] [J] (delete character I]-DP [I + 1] [J-1] (delete character I and J, which overlap the previous two) + [DP [I + 1] [J-1] + 1] (I and j are not deleted because s [I] And s [J] are equal, therefore, it is okay not to remove them. Adding 1 indicates that the middle is an empty string ).

If s [I ]! = S [J ], DP [I] [J] = DP [I] [J-1] + dp [I + 1] [J]-DP [I + 1] [J];

Use long, because the power of 60 in the worst case 2 exceeds Int.


Code:

#include <cstdio>#include <cstring>const int N = 65;typedef long long ll;ll dp[N][N];char str[N];void init () {int n = strlen (str);memset (dp, -1, sizeof (dp));for (int i = 0; i < n; i++)dp[i][i] = 1;}ll DP (int x, int y) {ll& ans = dp[x][y];if (ans !=-1)return ans;if (str[x] == str[y])return ans = DP(x, y - 1) + DP(x + 1, y) + 1;else {if (x + 1 <= y - 1)return ans = DP(x, y - 1) + DP(x + 1, y) - DP(x + 1, y - 1);elsereturn ans = DP(x, y - 1) + DP(x + 1, y);}}int main () {int t;scanf ("%d", &t);while (t--) {scanf ("%s", str);init ();printf ("%lld\n", DP (0, strlen (str) - 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.