Poj-1159-palindrome (LCS + optimization)

Source: Internet
Author: User


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)

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.