Answer: http://poj.org/problem? Id = 1458
Description:
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. given a sequence X = <x1, x2 ,..., XM> another sequence z = <Z1, Z2 ,..., ZK> is a subsequence of X if there exists a strictly increasing sequence <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 two sequences x and y the problem is to find the length of the maximum-length common subsequence of X and Y.
Input:
The program input is from the STD input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output:
For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample input:
Abcfbc abfcab
Programming Contest
ABCD MNP
Sample output:
4
2
0
Analysis: (LCS algorithm)
Given a sequence XM = (x1, x2 ,..., XM), we define the I-th prefix of XM:
Xi = (x1, x2 ,..., Xi) I = 0, 1, 2 ,..., M
C [I, j] is the sequence xi = (x1, x2 ,..., Xi) and YJ = (Y1, Y2 ,..., The length of the longest common subsequence of YJ.
Set sequence XM = {x1, x2 ,..., Xm} and YN = {y1, Y2 ,..., One of the longest common subsequences of yn} is zk = {Z1, Z2 ,..., ZK}, then
1. If XM = YN,
Then zk = XM = YN, And the Zk-1 is the longest common subsequence of Xm-1 and Yn-1.
2. If XM is less than YN and ZK is less than XM,
ZK is the longest common subsequence of Xm-1 and YN.
3. If XM is less than YN and ZK is less than YN,
ZK is the longest common subsequence of XM and Yn-1.
Generation:
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#define MAXN 1010#define RST(N)memset(N, 0, sizeof(N))using namespace std;char s1[MAXN], s2[MAXN];int lcs[MAXN][MAXN], L1, L2;int max(int x, int y) { return x > y ? x : y; }int LCS(){ L1 = strlen(s1+1), L2 = strlen(s2+1); for(int i=0; i<=L1; i++) lcs[i][0]=0; for(int i=0; i<=L2; i++) lcs[0][i]=0; for(int i=1; i<=L1; i++) { for(int j=1; j<=L2; j++) { if(s1[i] == s2[j]) lcs[i][j]=lcs[i-1][j-1]+1; else lcs[i][j]=max(lcs[i-1][j], lcs[i][j-1]); } } return lcs[L1][L2];}int main(){ while(~scanf("%s %s", s1+1, s2+1)) { printf("%d\n", LCS()); } return 0;}
Poj 1458 & HDU 1159 common subsequence (longest common subsequence) DP