最长公共子序列
来源:互联网 发布:淘宝电商怎么做大的 编辑:程序博客网 时间:2024/06/03 14:08
Common Subsequence
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 51421 Accepted: 21197
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.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
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 Input
abcfbc abfcabprogramming contest abcd mnp
Sample Output
420
令maxlen[i][0],maxlen[0][j]都等于零
递推公式
if(str1[i-1]==str2[j-1])
maxlen[i][j]=maxlen[i-1][j-1]+1;
else
maxlen[i][j]=max(maxlen[i-1][j],maxlen[i][j-1]);
注:当str1[i-1]!=str2[j-1]时,maxlen[str1][str2]不会比maxlen[str1-1][str2],maxlen[str1][str2-1两者之间任意一个小,也不会比两个大。
#include <iostream>#include <cstring>using namespace std;char str1[1000];char str2[1000];int maxlen[1000][1000];int main(){ while(cin >>str1>>str2) { int strlen1=strlen(str1); int strlen2=strlen(str2); for(int i=0;i<=strlen1;i++) maxlen[i][0]=0; for(int j=0;j<=strlen2;j++) maxlen[0][j]=0; for(int i=1;i<=strlen1;i++) for(int j=1;j<=strlen2;j++) { if(str1[i-1]==str2[j-1]) maxlen[i][j]=maxlen[i-1][j-1]+1; else maxlen[i][j]=max(maxlen[i-1][j],maxlen[i][j-1]); } cout<<maxlen[strlen1][strlen2]<<endl; } return 0;}演示图:
0 0
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列...
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- 最长公共子序列
- redis hello world 及设置
- CF#348 A. Mafia(二分,思维)
- git常用命令
- 乐理简单知识
- 17th浙大校赛 ZOJ3952 Fibonacci Sequence Chicken Edition【汇编】
- 最长公共子序列
- monkey初级
- spring中Aop的理解和例子
- 快来看看Google出品的Protocol Buffer,别只会用Json和XML了
- 浅谈对 this 指向的理解
- Android 数据存储和访问
- tomcat配置https
- 机械臂的moveit驱动
- C语言写getline(节省空间)