Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 17510 Accepted Submission(s): 7346
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
题目 要求是求出最长的公共字串,但是字串可以使分开的。
-----------------------------------------------------------------------------------------------------------------------------------------------------------
本题是动态规划的经典题目,求两个字符串的最长公共子序列,关于求单个字符串的最长有序子序列(较为简单),请看文章:[ACM_POJ_2533]Longest Ordered Subsequence。
思路分析:
设c[i][j]为字符串a的第i个字符与字符串b的第j个字符为止的最长公共子序列长度,那么有两种情况:
- 当a[i] == b[j]时,c[i][j]应该是前一个状态的最长公共子序列长度 + 1,而前一个状态是c[i - 1][j]呢,还是c[i][j - 1]?两者都不是,因为a[i]与b[j]匹配,a[i]与b[j]必然不能已经匹配过,否则就是同一个字母匹配了多次,这必然是非法的,因此上一个状态应是c[i - 1][j - 1],即c[i][j] = c[i - 1][j - 1] + 1;
- 当a[i] != b[j]时,上一个状态可能是c[i - 1][j]或c[i][j - 1],而既然要找最长公共子序列,自然是找最大的一个,即c[i][j] = max(c[i - 1][j], c[i][j - 1])。
这段讲解 比较清楚,一开始接触dp,还没有建立这方面的思想,慢慢来吧。
#include<iostream>
#include<string>
using namespace std;
char a[500],b[500];
int dp[500][500];
int main()
{
int m,n,i,j;
while(scanf("%s%s",a,b)!=EOF)
{
m=strlen(a);
n=strlen(b);
memset(dp,0,sizeof(dp));
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(a[i-1]==b[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
}
else
{
dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
}
}
}
cout<<dp[m][n]<<endl;
}
}