Poj1458--Common Subsequence(LCS模板)

Common Subsequence
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 43212   Accepted: 17527

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

Source

 
LCS 算法
首先,考虑如何递归地计算 LCS。令:

C1 是 S1 最右侧的字符
C2 是 S2 最右侧的字符
S1' 是 S1 中 “切掉” C1 的部分
S2' 是 S2 中 “切掉” C2 的部分
有三个递归子问题:

L1 = LCS(S1', S2)
L2 = LCS(S1, S2')
L3 = LCS(S1', S2')
结果表明(而且很容易使人相信)原始问题的解就是下面三个子序列中最长的一个:

L1
L2
如果 C1 等于 C2,则为 L3 后端加上 C1 ,如果 C1 不等于 C2,则为 L3。
(基线条件(base case)是 S1 或 S2 为长度为零的字符串的情形。在这种情况下,S1 和 S2 的 LCS 显然是长度为零的字符串。)
LCS算法
 
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #define max(a, b) a>b?a:b
 5 using namespace std;
 6 char s1[1010], s2[1010];
 7 int dp[1010][1010];
 8 int main()
 9 {
10     while(~scanf("%s %s", s1, s2))
11     {
12         memset(dp, 0, sizeof(dp));
13         int len1 = strlen(s1);
14         int len2 = strlen(s2);
15         int i, j;
16         for(i = 1; i <= len1; i++)
17         {
18             for(j = 1; j <= len2; j++)
19             {
20                 if(s1[i-1] == s2[j-1])
21                     dp[i][j] = dp[i-1][j-1] + 1;
22                 else
23                     dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
24             }    
25         }    
26         printf("%d
", dp[len1][len2]);
27     } 
28     return 0;
29 }
原文地址:https://www.cnblogs.com/soTired/p/4717476.html