Question: How many characters can be added to a string to make it a return string?
Idea: the obvious equation is: DP [I] [J] = min {DP [I + 1] [J], DP [I] [J-1], DP [I + 1] [J-1] (STR [I] = STR [J )}
DP [I] [J] indicates that the characters from I to J are constructed as the characters with the least number of characters added to the input string, but discuss says that this will exceed space + timeout
After observing this equation, the three sub-States are used each time, so the form of the equation is changed as appropriate:
DP [I] [J] indicates the minimum number of characters to be added to a string consisting of substrings whose start length is J, the equation becomes DP [I] [J] = min {DP [I + 1] [J-1], DP [I] [J-1], DP [I + 1] [J-2] (STR [I] = STR [J )}, recursive only need to store the length of J-1 and J-2 data can release the length of J data, using the pointer to change the order of the next three Arrays can be. As a result, the space problem was solved smoothly.
// Poj1159
# Include <cstdio>
# Include <string. h>
# Include <iostream>
Using namespace STD;
Const int maxn = 5009;
Int min (int A, int B)
{
If (A> B) return B; else return;
}
Int main ()
{
Int N;
Char STR [maxn];
Scanf ("% d % s", & N, STR );
Int A [maxn] = {0}, B [maxn] = {0}, C [maxn] = {0 };
Int * ans = A, * f = B, * FF = C, * temp;
For (int K = 1; k <= N; k ++)
{
For (INT I = 1; I <= n-k + 1; I ++)
{
Ans [I] = min (F [I], F [I + 1]) + 1;
If (STR [I-1] = STR [I + K-2]) ans [I] = min (ANS [I], FF [I + 1]);
}
Temp = ff; FF = f; F = ans; ans = temp;
}
Printf ("% d \ n", F [1]);
Return 0;
}
Poj1159: palindrome [DP]