Detailed problem solving report can see this PPT
This problem if is directly open int 5000 * 5000 space will certainly be mle, the optimization method is to use a scrolling array.
Original LCS transfer equation:
DP[I][J] = dp[i-1][j] + dp[i][j -1]
Because Dp[i][j] only depends on dp[i-1][j] and dp[i][j-1]
So you can use the scrolling array as follows:
Dp[i% 2][j] = dp[(i-1)% 2][j] + dp[i% 2][j-1]
Space-saving methods can be achieved
The answer is stored in dp[n% 2][n]
Source code:
//#pragma COMMENT (linker, "/stack:16777216")//For C + + Compiler#include <stdio.h>#include<iostream>#include<cstring>#include<cmath>#include<stack>#include<queue>#include<vector>#include<algorithm>#definell Long Long#defineMax (b) ((a) > (b))? (a): (b))#defineMin (b) ((a) < (a))? (a): (b))#defineAbs (x) (((x) > 0)? (x): (-(x)))using namespacestd;Const intINF =0x3f3f3f3f;Const intMAXN = -;intdp[2][5005];intMain () {intI, J, T, K, N, M; stringstr1, str2; while(EOF! = scanf ("%d",&N)) {cin>>str1; STR2=str1; Reverse (Str1.begin (), Str1.end ()); Memset (DP,0,sizeof(DP)); for(i =1; I <= N; ++i) { for(j =1; J <= N; ++j) { if(Str1[i-1] = = Str2[j-1]) {dp[i%2][J] = max (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]); } }} cout<< N-dp[n%2][n] << Endl;//answer = x.length ()-LCS (X, Y) } return 0;}
POJ 1159 back to text LCS scrolling array optimization