Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 21266 Accepted Submission(s): 9205
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 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.
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.
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0
Source
一道简单的求公共子序列的DP,比较好理解的是将题目所给的数据转化为1个矩阵,如图所示
两个字符串分别为行和列,如果相同,则值为1,否则,值为0。
那么,现在问题就转化成了求从矩阵左上角出发到矩阵右下角的和的最大值,而且只能往下或者往右走。
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char string1[1001];
char string2[1001];
int cnt[1001][1001];
int main()
{
int len1, len2;
while(scanf("%s%s", string1, string2) != EOF)
{
memset(cnt, 0, sizeof(cnt));
len1= strlen(string1);
len2 = strlen(string2);
for(int i=1; i<=len1; ++i)
{
for(int j=1; j<=len2; ++j)
{
if(string1[i - 1] == string2[j - 1])
cnt[i][j] = cnt[i - 1][j - 1] + 1;//如果相同,则值为1
else
cnt[i][j] = max(cnt[i][j - 1], cnt[i - 1][j]);
}
}//转化为矩阵之后的DP
printf("%d\n", cnt[len1][len2]);
}
return 0;
}