类型:DP
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1513
思路: 状态dp(i, j)表示从位置i到位置j最少需要插入的字符数
情况1:str[i] == str[j] 则dp(i, j) = min(dp(i, j), dp(i + 1, j - 1))
情况2:str[i] != str[j] 则dp(i, j) = min(dp(i, j), dp(i + 1, j))dp(i, j) = min(dp(i, j), dp(i, j - 1))
枚举长度,当要求长度为k的串的最优值时,长度为k - 1和k - 2的最优值已经求出
可以利用他们的最优值推导出当前最优值利用3行滚动数组来降低空间消耗,观察方程,当前情况下只会利用k - 1和k - 2的值
!!!k行计算完成时要清空k - 2行的数据,防止原来的值产生影响
#include <iostream>
#include <sstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <set>
#include <deque>
#include <bitset>
#include <functional>
#include <utility>
#include <iomanip>
#include <cctype>
using namespace std;
#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
#define max(a,b) ((a) > (b)) ? (a) : (b)
#define min(a,b) ((a) < (b)) ? (a) : (b)
#define CLR(a,b) memset(a,b,sizeof(a))
#define PB(x) push_back(x)
typedef vector<int> VI;
const int MAXN = 5010;
const int MAXM = 0;
const int hash_size = 25000002;
const int INF = 0x7f7f7f7f;
int n;
int dp[3][MAXN];
char str[MAXN];
int main()
{
int i, j, k;
int i1;
while(cin>>n) {
scanf("%s", str + 1);
FORE(i, 1, n)
dp[0][i] = dp[1][i] = dp[2][i] = INF;
FORE(i, 1, n)
dp[1][i] = 0;
FORE(i, 1, n - 1)
if(str[i] != str[i + 1])
dp[2][i]= 1;
else
dp[2][i] = 0;
FORE(k, 3, n) {
FORE(i, 1, n - k + 1) {
j = i + k - 1;
if(str[i] == str[j])
dp[k % 3][i] = min(dp[k % 3][i], dp[(k - 2) % 3][i + 1]);
dp[k % 3][i] = min(dp[k % 3][i], dp[(k - 1) % 3][i + 1] + 1);
dp[k % 3][i] = min(dp[k % 3][i], dp[(k - 1) % 3][i] + 1);
}
FORE(i1, 1, n)
dp[(k + 1) % 3][i1] = INF;
}
cout<<dp[n % 3][1]<<endl;
}
return 0;
}