POJ-1159-Palindrome (LCS + optimization)
Train of Thought: I think the question is clear, that is, to find the longest common subsequence of string s and string t after string s is reversed, but I think the space overhead is a bit large, if you open the int, it will pop up. 5000*5000 has mb. Here you can open the short int, which is almost the same. Another way is to get a rolling array, because the LCS, according to the state transition equation, you can know that you only need the first row and the current row, so it is OK to open 2*5005. For details, refer to the code.
AC code ①:
#include
#include
#include
#include #include
#include
#include
#include
#include
#include
#include
#include
#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
#include
#include
#include #include
#include
#include
#include
#include
#include
#include
#include
#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;}