题目链接:http://poj.org/problem?id=1159
解题报告:
1、LCS的状态转移方程为
if(str[i-1]==str[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
2、由于开不了dp[5005][5005],于是考虑到压缩状态
这里采用滚动数组方式,LCS的状态转移方程可以改写为
if(str1[i-1]==str2[j-1]) { 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]);
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
#define MAX 5005
using namespace std;
///LCS的状态转移方程,d[i][j]=max(d[i-1][j],d[i][j-1]);
///LCS的滚动数组形式的状态转移方程,d[i%2][j]=max(d[(i-1)%2][j],d[i%2][j-1])
int dp[2][MAX];///滚动数组
int main()
{
char str1[MAX],str2[MAX];
int n;
cin>>n;
cin>>str1;
for(int i=0; i<n; i++)
str2[n-i-1]=str1[i];
memset(dp,0,sizeof(dp));
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(str1[i-1]==str2[j-1])
{
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]);
}
}
printf("%d\n",n-dp[n%2][n]);
return 0;
}
原文:http://www.cnblogs.com/TreeDream/p/5229050.html