http://poj.org/problem?id=1458
Common Subsequence
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 35449 | Accepted: 14100 |
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, x
ij = 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
引进一个二维数组c[][],用c[i][j]记录X[i]与Y[j] 的LCS 的长度,b[i][j]记录c[i][j]是通过哪一个子问题的值求得的,以决定搜索的方向。
我们是自底向上进行递推计算,那么在计算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]。
问题的递归式写成:
详细结题报告:
http://blog.csdn.net/yysdsyl/article/details/4226630
代码:
/*
Source Code
Problem: 1458 User: 201392210
Memory: 4120K Time: 32MS
Language: C++ Result: Accepted
*/
#include <cstdio>
#include <iostream>
#include <cmath>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=1000;
char x[maxn],y[maxn];
int l1,l2;
int dp[maxn][maxn];
void lcs()
{
memset(dp,0,sizeof(dp));
for (int i = 1; i <= l1; ++i)
{
for (int j = 1; j <= l2; ++j)
{
if(x[i-1]==y[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
}
}
}
int main()
{
freopen("input.txt","r",stdin);
while(~scanf("%s%s",x,y))
{
l1=strlen(x);
l2=strlen(y);
lcs();
cout<<dp[l1][l2]<<endl;
}
return 0;
}