Title Link: http://poj.org/problem?id=1159
Problem Solving Report:
1. The state transfer equation of LCS is
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, because can not open dp[5005][5005], so consider the compression state
Using the rolling array method, the state transfer equation of LCS can be rewritten as
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[(-1)%2][j],dp[i%2][j-1 ]);
#include <stdio.h> #include <algorithm> #include <string.h> #include <iostream> #define MAX 5005using namespace Std;///lcs state transfer equation, D[i][j]=max (d[i-1][j],d[i][j-1]),///lcs of the state transfer equation in the form of a rolling array, D[i%2][j]=max (d[(i-1 )%2][j],d[i%2][j-1]) int dp[2][max];///Scroll array 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;}
Dynamic Programming (DP), compressed state, inserting characters to form palindrome strings