Problem Description
A subsequence of agiven sequence is the given sequence with some elements (possible none) leftout. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1,z2, ..., zk> is a subsequence of X if there exists a strictly increasingsequence <i1, i2, ..., ik> of indices of X such that for all j =1,2,...,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X= <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given twosequences X and Y the problem is to find the length of the maximum-lengthcommon subsequence of X and Y.
The program input is from a text file. Each data set in the file contains twostrings representing the given sequences. The sequences are separated by anynumber of white spaces. The input data are correct. For each set of data theprogram prints on the standard output the length of the maximum-length commonsubsequence from the beginning of a separate line.
Sample Input
abcfbc abfcab
programmingcontest
abcd mnp
Sample Output
4
2
0
一道裸的最长公共子序列问题
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<string>
using namespace std;
int dp[1010][1010];
char str1[1010] ,str2[1010];
int main()
{
string a ,b;
int lena ,lenb;
while(~scanf("%s%s",&str1,&str2))
{
a = str1;
b = str2;
a = ' ' + a;
b = ' ' + b;
lena = a.length();
lenb = b.length();
memset(dp,0,sizeof(dp));
for(int i = 1;i < lena;i++)
{
for(int j = 1;j < lenb;j++)
{
if(a[i]==b[j])
{
if(dp[i][j] < dp[i-1][j-1] + 1)
{
dp[i][j] = dp[i-1][j-1] + 1;
}
}
else
{
if(dp[i][j-1] < dp[i-1][j])
{
dp[i][j] = dp[i-1][j];
}
else
{
dp[i][j] = dp[i][j-1];
}
}
}
}
printf("%d\n",dp[lena-1][lenb-1]);
}
return 0;
}