Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 12473 - Common Palindrome
Source : UVA Online Judge
Category : Dynamic Programing
Algorithm : Dynamic Programing
Verdict : Accepted
- #include <bits/stdc++.h>
-
- using namespace std;
-
- #define max3(a, b, c) max(a, max(b, c))
-
- static const int maxn = 62;
-
- string A, B;
- int lenA, lenB;
-
- int dp[maxn][maxn][maxn][maxn];
- bool memoize[maxn][maxn][maxn][maxn];
-
- int solve(int i, int j, int k, int l)
- {
- if (i > j || k > l) return 0;
- if (i == j && (A[i] == B[k] || A[i] == B[l])) return 1;
- if (k == l && (A[i] == B[k] || A[j] == B[k])) return 1;
- int &ret = dp[i][j][k][l];
- bool &mem = memoize[i][j][k][l];
- if (mem == 1) return ret;
- mem = 1;
- if (A[i] == A[j] && B[k] == B[l] && A[i] == B[k])
- {
- ret = 2 + solve(i+1, j-1, k+1, l-1);
- }
- else
- {
- int choice1 = solve(i+1, j, k, l);
- int choice2 = solve(i+1, j, k+1, l);
- int choice3 = solve(i+1, j, k, l-1);
- int choice4 = solve(i+1, j, k+1, l-1);
-
- int choice5 = solve(i, j-1, k, l);
- int choice6 = solve(i, j-1, k+1, l);
- int choice7 = solve(i, j-1, k, l-1);
- int choice8 = solve(i, j-1, k+1, l-1);
-
- int choice9 = solve(i, j, k+1, l);
- int choice10 = solve(i+1, j, k+1, l);
- int choice11 = solve(i, j-1, k+1, l);
- int choice12 = solve(i+1, j-1, k+1, l);
-
- int choice13 = solve(i, j, k, l-1);
- int choice14 = solve(i+1, j, k, l-1);
- int choice15 = solve(i, j-1, k, l-1);
- int choice16 = solve(i+1, j-1, k, l-1);
-
- int maxi = max(choice1, choice2);
- maxi = max3(maxi, choice3, choice4);
- maxi = max3(maxi, choice5, choice6);
- maxi = max3(maxi, choice7, choice8);
- maxi = max3(maxi, choice9, choice10);
- maxi = max3(maxi, choice11, choice12);
- maxi = max3(maxi, choice13, choice14);
- maxi = max3(maxi, choice15, choice16);
-
- ret = maxi;
- }
- return ret;
- }
-
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- cout.tie(NULL);
-
- int tc;
- cin >> tc;
- for (int tcase = 1; tcase <= tc; tcase++)
- {
- cin >> A >> B;
- lenA = A.length();
- lenB = B.length();
- memset(memoize, 0, sizeof memoize);
- cout << "Case " << tcase << ": " << solve(0, lenA-1, 0, lenB-1) << '\n';
- }
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.