动态规划
最长公共子序列
1510: Common Subsequence
描述:
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 input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
输出:
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.
题目链接:link
解题分析:
设两个序列X={x1,x2,x3…xn},Y={y1,y2,y3…yn}。用LSC(X,Y)表示最长公共子序列。
1.如果xn=yn。则该元素一定存在于公共子序列中,所以可化为寻求子问题LSC(X-1,Y-1)。
用公式可表示为LSC(X,Y)=LSC(X-1,Y-1)+1。
2.如果xn!=yn。则该元素不存在于公共子序列中,所以转而去寻求两个子问题,即LSC(X-1,Y)和LSC(X,Y-1)。其中,X-1={x1,x2,x3…xn-1},Y-1={y1,y2,y3…yn-1}。
用公式可表示为LSC(X,Y)=max(LSC(X-1,Y),LSC(X,Y-1))。
AC代码:
#include <stdio.h>
#include <string.h>
int max(int a,int b)
{
return a>b?a:b;
}
char a[1005],b[1005];
int d[1005][1005];
int main()
{
int l1,l2,i,j;
while(scanf("%s %s",a+1,b+1)!=EOF)
{
l1=strlen(a+1);
l2=strlen(b+1);
memset(d,0,sizeof(d));
for(i=1;i<=l1;i++)
{
for(j=1;j<=l2;j++)
{
if(a[i]==b[j])
d[i][j]=d[i-1][j-1]+1;
else
d[i][j]=max(d[i-1][j],d[i][j-1]);
}
}
printf("%d\n",d[l1][l2]);
}
return 0;
}