Longest common sub-sequenceTime limit: Ms | Memory limit: 65535 KB Difficulty: 3 Description Let's not beat around the bush, title, all you need to do is write a program that will draw the longest common subsequence.
Tip: The longest common subsequence is also known as the longest common substring (not requiring continuous), and the abbreviation is LCS (longest Common subsequence). It is defined as a sequence s, if it is a subsequence of two or more known sequences, and is the longest of all conforming to this condition sequence, then S is called the longest common subsequence of the known sequence. Enter the first line to give an integer N (0<n<100) to indicate the number of data groups to be tested
The next two lines of data are two sets of strings to be tested. Each string length is not greater than 1000. Output each set of test data outputs an integer representing the longest common subsequence length. One row for each group of results. Sample input
2
asdf
adfsd
123abc
abc123abc
Sample output
3
6
/* To find the longest common sub-sequence. Dynamic planning issues.
Set sequence x = (x1; x2; ...; xm) and y = (y1; y2; ...; yn) the longest public sub-order listed as
Z = (z1; z2; ...;; zk),
The
. If xm = yn, then zk = XM = yn, and Zk-1 is the longest common subsequence of Xm-1 and Yn-1.
. If xm! = yn and zk! = XM, then z is the longest common subsequence of Xm-1 and Y.
. If xm! = yn and zk! = yn, then z is the longest common subsequence of X and Yn-1.
Among them Xm-1 = (x1; x2; ...;; xm-1), Yn-1 = (y1; y2; ....; yn-1), Zk-1 = (z1; Z2;..;; zk-1)
*/
The general solution, does not optimize the space.
#include <stdio.h>
#include <string.h>
#define MAX 1010
int Dp[max][max] = {0};
void LCS (const char *x, int m, const char *y, int n)
{
int i,j;
for (i=0; i<=m; i++)
{
dp[i][0] = 0;
}
for (j=0;j<=n; j + +)
{
dp[0][j] = 0;
}
For (I=1, i<=m; i++)
{for
(j=1; j<=n; j + +)
{
if (x[i-1] = = Y[j-1])
{
Dp[i][j] = dp[i -1][J-1] + 1;
}
else
{
Dp[i][j] = Dp[i-1][j] > dp[i][j-1]?dp[i-1][j]: dp[i][j-1];
}}} int main ()
{
int m;
Char X[max],y[max];
scanf ("%d", &m);
while (m--)
{
int xlen,ylen;
scanf ("%s%s", X, y);
Xlen = strlen (x);
Ylen = strlen (y);
LCS (X,xlen,y,ylen);
printf ("%d\n", Dp[xlen][ylen]);
}
return 0;
}
Scrolling arrays, optimizing space
#include <stdio.h>
#include <string.h>
#define MAX 1001 short
Dp[2][max];
int main ()
{
int m;
Char X[max],y[max];
scanf ("%d", &m);
while (m--)
{
int xlen,ylen;
int i,j,e = 0;
scanf ("%s%s", X, y);
Xlen = strlen (x);
Ylen = strlen (y);
Memset (Dp,0,sizeof (DP));
for (I=1; i<=xlen;i++)
{
e = 1-e;
for (j=1; j<=ylen; j + +)
{
if (x[i-1] = = Y[j-1])
{
dp[e][j] = dp[1-e][j-1] + 1;
}
else
{
Dp[e][j] = dp[e][j-1] > dp[1-e][j]?dp[e][j-1]: dp[1-e][j];}}
}
printf ("%d\n", Dp[e][ylen]);
}
return 0;
}