动态规划练习 8
题目:Palindrome (POJ 1159)
链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=1159
#include <iostream>
#include <string>
#include <memory.h>
#include <algorithm>
using namespace std;
short min_fix[5001][5001];
int min_fix_char_recursion(const char *input, int i, int j)
{
if (i < j)
{
if (input[i] != input[j])
{
return min(
min_fix_char_recursion(input, i + 1, j),
min_fix_char_recursion(input, i, j - 1)) + 1;
}
else
{
return min_fix_char_recursion(input, i + 1, j - 1);
}
}
return 0;
}
int main(int argc, char **argv)
{
int n;
string input;
cin >> n;
cin >> input;
memset(min_fix, 0, sizeof(min_fix));
if (input.size() >= 3 && input.size() <= 5000)
{
// recursion version.
// cout << min_fix_char_recursion(input.c_str(), 0, input.size() - 1) << endl;
// recursion ends at any positions in input string.
// so, dp begins at any positions in input string.
for (int i = (int)input.size() - 1; i >= 0; --i)
{
for (int j = i + 1; j < (int)input.size(); ++j)
{
if (input[i] == input[j])
{
min_fix[i][j] = min_fix[i + 1][j - 1];
}
else
{
min_fix[i][j] = min(min_fix[i + 1][j], min_fix[i][j - 1]) + 1;
}
}
}
cout << min_fix[0][input.size() - 1] << endl;
}
return 0;
}