Test instructions: A string of n long (3 <= n <= 5000), asking at least how many characters are inserted to make it into a palindrome.
Title Link: http://poj.org/problem?id=1159
-->> State: Dp[i][j] represents the number of characters from the I-character to the J-character into the fewest inserts of a palindrome.
State transition equation:
If sz[i] = = Sz[j], then: dp[i][j] = dp[i + 1][j-1];
otherwise: dp[i][j] = min (dp[i + 1][j], dp[i][j-1]) + 1;
Submit, 5000 * 5000 int--> * 4 bytes approx (/(2 ^ 20)) equals 5 * 5 * 4 MB = MB > 65536 K = + M, will mle.
If open to short, about 50M < 64M, can be Oh! Not bad!
Better way to optimize with the idea of scrolling arrays.
#include <cstdio> #include <algorithm>using std::min;const int maxn = 1;char Sz[maxn];int dp[2][maxn];v OID Dp (int N) { int nstate = 0; for (int i = N-1; I >= 0; i.) { dp[1 ^ nstate][i] = 0; for (int j = i + 1; j < N; ++j) { if (sz[i] = = Sz[j]) { dp[1 ^ nstate][j] = Dp[nstate][j-1]; } Else { dp[1 ^ nstate][j] = min (dp[nstate][j], dp[1 ^ nstate][j-1]) + 1; } } Nstate ^= 1; } printf ("%d\n", Dp[nstate][n-1]);} int main () { int N; while (scanf ("%d", &n) = = 1) { scanf ("%s", SZ); Dp (N); } return 0;}
Open short to the wording of AC:
#include <cstdio> #include <algorithm>using std::min;const int maxn = 1;char Sz[maxn];short dp[maxn][ma Xn];void Dp (int N) {for (int i = 0; i < N; ++i) {dp[i][i] = 0; if (i + 1 < N) {if (sz[i] = = sz[i + 1]) {dp[i][i + 1] = 0; } else {dp[i][i + 1] = 1; }}} for (int nlen = 3, Nlen <= N; ++nlen) {for (int i = 0; i < n; ++i) { Int J = i + nLen-1; if (J >= N) break; if (sz[i] = = Sz[j]) {Dp[i][j] = dp[i + 1][j-1]; } else {Dp[i][j] = min (dp[i + 1][j], dp[i][j-1]) + 1; }}}}void Output (int N) {printf ("%d\n", Dp[0][n-1]);} int main () {int N; while (scanf ("%d", &n) = = 1) {scanf ("%s", SZ); Dp (N); Output (N); } return 0;}
Poj-1159-palindrome (scroll array dp)