Topic Transfer: Palindrome
idea: A look at the topic is clear, is to find the string s and inverted s string t the longest common sub-sequence, but a look at the space overhead is a bit large, if open int will explode, 5000*5000 has 100MB, here can open short int, almost right to the past, there is a way to get a scrolling array, because the LCS, according to the state transfer equation can be known, only the previous row and the current line, so open a 2*5005 is OK, specific look at the code
AC Code ①:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set > #include <deque> #include <cctype> #define LL long long#define INF 0x7fffffffusing namespace Std;char s[ 5005];char T[5005];short int Dp[5005][5005];int main () {int n;cin >> n;scanf ("%s", S + 1); for (int i = 1; I <= N; i + +) {t[n-i + 1] = s[i];} T[n + 1] = ' + '; for (int i = 1; I <= n; i + +) {for (int j = 1; J <= N; j + +) {if (s[i] = = T[j]) {Dp[i][j] = Dp[i-1][j-1 ] + 1;} else {Dp[i][j] = max (Dp[i-1][j], dp[i][j-1]);}}} cout << N-dp[n][n] << endl;return 0;}
AC Code ②:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set > #include <deque> #include <cctype> #define LL long long#define INF 0x7fffffffusing namespace Std;int dp[2] [5005];char S[5005];char T[5005];int Main () {int n;cin >> n;scanf ("%s", S + 1); for (int i = 1; I <= N; i + +) {T[n + 1-i] = s[i];} T[n + 1] = ' + '; for (int i = 1; I <= n; i + +) {for (int j = 1; J <= N; j + +) {if (s[i] = = T[j]) {dp[i% 2][j] = dp[(i- 1)% 2][j-1] + 1;} else {dp[i% 2][j] = max (dp[(i-1)% 2][j], dp[i% 2][j-1]);}} cout << n-dp[n% 2][n] << Endl;return 0;}
Poj-1159-palindrome (LCS + optimization)