Brief Description: The LCS problem, the longest common subsequence problem, given two sequences x={x1, X2, ..., XM} and Y={y1, y2, ..., yn}, for the longest common subsequence of x and Y. Similar to LIS, LCS can also be discontinuous.
Problem- Solving ideas: I think the introduction of algorithms in this issue is very good, so I am mainly in the collation.
1, first of all we consider the method of brute force search solution, we want to violently enumerate all the sub-sequences of X, and then see if it is also a sub-sequence of y, such a method, it is obvious that time complexity refers to a number of levels, it is not advisable, but we can see what it?
2. Let's look at whether the LCS has the optimal sub-structure:
What is the solution to the violence before, and how is it expressed in the program? Consider a sequence of z={z1, Z2, ..., ZK}, which is an LCS sequence for x and y:
If Xm==yn, it means that XM must be in the z sequence, and it is ZK;
If Xm!=yn, then it is stated that XM and yn have at most one in Z, so there are two possibilities for LCS X and Y here: X (1...m-1) and Y (1...N) LCS and X (1...M) and Y (1...n-1) LCS;
So there is the best substructure!
3, from the above can be seen, yes, is deep search! But, it's too slow. So, the memory of a bit on the line!
So...... Using Dp[i][j] to represent the X (1...i) and Y (1...J) LCS, then there is the state transition equation :
if(x[i]==y[j]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
Complete code:(can be tested with poj_1458)
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>Using namespace Std;int m,n,x[1005],y[1005],ans,dp[1005][1005];char St1[1005],st2[1005];int Main () {while (~scanf ("%s%s", st1,st2)) {M=strlen (ST1), N=strlen (ST2);for (int i=0;i<m;i++)X[i+1]=st1[i];for (int i=0;i<n;i++)Y[i+1]=st2[i];ans=0;memset (Dp,0,sizeof (DP));for (int i=1;i<=m;i++) {for (int j=1;j<=n;j++) {if (X[i]==y[j])dp[i][j]=dp[i-1][j-1]+1;ElseDp[i][j]=max (dp[i-1][j],dp[i][j-1]); } }printf ("%d\n", Dp[m][n]); }return 0;}
Summary:
1, has not known the LCS is what, today is to understand a bit;
2, sure enough deep search is the kingly Ah!
LCS problem--Dynamic planning