#原题:
- Problem 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.
The program…
- Sample Input
abcfbc abfcab
programming contest
abcd mnp
- Sample Output
4
2
0
###解题思路:
- 可以把c[ i ][ j ]理解成:取X的前i个字符和取Y的前j个字符,能得到的LCS值
- 分为一下两类:
- 如果X的第i个字符X[ i ] 等于 Y的第j个字符Y[ j ]
- 如果X的第i个字符X[ i ] 不等于 Y的第j个字符Y[ j ]
引进一个二维数组c[ ][ ],用c[ i ][ j ]记录X[ i ]与Y[ j ] 的LCS 的长度。
我们是自底向上从小到大进行递推计算,所以就能在在计算c[ i ][ j ]之前,把c[ i-1 ][ j-1 ],c[ i-1 ][ j ]与c[ i ][ j-1 ]计算出来,此时我们根据X[ i ] = Y[ j ]还是X[ i ] != Y[ j ],就可以计算出c[ i ][ j ]。
###代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[1000][1000];
char a[1000], b[1000];
int main()
{
int a_length, b_length, maxLength, i, j;
while (scanf("%s%s",a + 1,b + 1)!=EOF)//0位不存
{
a[0] = b[0] = '*';//无用--只是方便下面数组循环无需减一加一操作
a_length = strlen(a);
b_length = strlen(b);
maxLength = max(a_length, b_length);
for (i = 0; i <= maxLength; i++)
dp[i][0] = dp[0][i] = 0;//初始化
for (i = 1; i < a_length; i++)//动态规划
for (j = 1; j < b_length; j++)
if (a[i] == b[j])dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
printf("%d\n", dp[i - 1][j - 1]);
}
}