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;}