Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 2 Accepted Submission(s) : 1
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.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
Source
Southeastern Europe 2003
这是我接触的第一道动态规划题(大概)。
说一下我的理解,这道题找的是最长公共子序列,不是子串,按照题目给的样例abcfbc abfcab,其中按照顺序,且两个字符串都有的是abfc,即abcfbc 、abfcab。
假设有2个长度为N的字符串A和B,找A和B的最长公共子序列可以分解成一个个小问题,结合图片细分情况。
…表示←和↑都可以
col[1]==row[1],dp[1][1]=dp[0][0]+1,即col[i]==row[j],(i,j>=1),有dp[i][j]=dp[i-1][j-1]+1。
col[i]!=row[j],dp[i][j]=max(dp[i-1][j],dp[i][j-1])。
最后,dp[i][j]的值为最长子序列
C
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
char a[1000],b[1000];
int dp[1001][1001]; //dp数组开小点,我刚开始开了10000x10000,报了MLE
int max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
int main(void)
{
int r,c,len1,len2;
while(scanf("%s %s",a,b)!=EOF)
{
memset(dp,0,sizeof(dp));
len1=strlen(a);
len2=strlen(b);
for(r=1;r<=len1;r++)
{
for(c=1;c<=len2;c++)
if(a[r-1]==b[c-1])//注意dp数组记录数据是从1开始,而字符串存储是从0开始
dp[r][c]=dp[r-1][c-1]+1;
else
dp[r][c]=max(dp[r-1][c],dp[r][c-1]);
}
printf("%d\n",dp[len1][len2]);
}
return 0;
}