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.
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 Output
420
題意:
我們稱序列 Z = < z1, z2, ..., zk >是序列X = < x1, x2, ..., xm >的子序列當且僅當存在嚴格上升的序列< i1, i2, ..., ik >,使得對j = 1, 2, ... ,k, 有xij = zj。比如Z = < a, b, f, c > 是X = < a, b,c, f, b, c >的子序列。現在給出兩個序列X
和Y,你的任務是找到X 和Y 的最大公共子序列,也就是說要找到一個最長的序列Z,使得Z 既是X 的子序列也是Y 的子序列.
思路:
設d(i,j)爲A1,A2,...Ai和B1,B2,..Bj的LCS的長度,則當A[i]=A[j]時d(I,j)d(i-1,j-1)+1,否則d(i,j)=max{d(i-1,j),d(i,j-1)},時間複雜度爲O(nm),其中n和m分別是序列A和B的長度。
代碼:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m;
int const maxn=1000;
char s[maxn],t[maxn];
int dp[maxn+1][maxn+1];
void solve()
{
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(s[i]==t[j])
{
dp[i+1][j+1]=dp[i][j]+1;
}
else
{
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
}
}
}
printf("%d\n",dp[n][m]);
}
int main()
{
while(scanf("%s%s",&s,&t)!=EOF)
{
n=strlen(s);
m=strlen(t);
solve();
}
return 0;
}