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

解题思路:基础dp!求两个字符串的最长公共子序列的长度,则dp[i][j]表示字符串s1的前i个字符与字符串s2的前j个字符构成的最长公共子序列的长度,推导式:当s1的第i个字符与s2的第j个字符相等时,dp[i][j]=dp[i-1][j-1]+1;否则dp[i][j]=max(dp[i-1][j],dp[i][j-1]),表示当前的dp[i][j]为s1的前i-1个字符与s2的前j个字符组成的最长公共子序列的长度即dp[i-1][j]和s1的前i个字符与s2的前j-1个字符组成的最长公共子序列的长度即dp[i][j-1]这两者中的最大值。dp求解的核心就是枚举到当前字符串中的某个字符,都要枚举另外一个字符串中的每个字符,并记录当前的最优解,这样最后求得dp[len1][len2]就是LCS的长度。时间复杂度是O(nm)。

AC代码:

 #include<bits/stdc++.h>
using namespace std;
const int maxn=;
char s1[maxn],s2[maxn];int len1,len2,dp[maxn][maxn];
int main(){
while(cin>>(s1+)>>(s2+)){
memset(dp,,sizeof(dp));
len1=strlen(s1+),len2=strlen(s2+);
for(int i=;i<=len1;i++){
for(int j=;j<=len2;j++){
if(s1[i]==s2[j])dp[i][j]=dp[i-][j-]+;
else dp[i][j]=max(dp[i-][j],dp[i][j-]);
}
}
cout<<dp[len1][len2]<<endl;
}
return ;
}

最新文章

  1. ASP.NET Aries JSAPI 文档说明:AR.DataGrid
  2. 【ASP.NET】利用Nuget打包package——命令行方式
  3. 大熊君学习html5系列之------History API(SPA单页应用的必备)
  4. AChecker + Selenium2对需要登录的页面进行自动化可访问性测试
  5. C++控制程序只运行一个实例
  6. ORACLE CLIENT客户端安装步骤详解
  7. cin 对象取值过程详解
  8. C语言中变量的作用域和生命周期
  9. python命令行参数解析模块argparse和docopt
  10. edgedb 集成timescaledb
  11. A1009. Product of Polynomials
  12. win7下Google谷歌浏览器上传下载卡死无响应
  13. 查询数据库中含clob,blob的表
  14. scala变量类型和性质
  15. 查看项目中的laravel的版本
  16. Spring Boot + MyBatis + Pagehelper 配置多数据源
  17. 20165218 《网络对抗技术》Exp4 恶意代码分析
  18. 微信小程序实现文字跑马灯
  19. 为什么JSP会比Beetl慢
  20. 多种移动平均计算总结(MA,EMA,SMA,DMA,TMA,WMA)

热门文章

  1. 用Visual Studio高版本号打开低版本号的project,转换时出现错误:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
  2. gbk转utf-8 iconv 编码转换
  3. POJ训练计划2299_Ultra-QuickSort(线段树/单点更新)
  4. 亲測Mysql表结构为InnoDB类型从ibd文件恢复数据
  5. Java 中 泛型的限定
  6. 数据库建表参考(SQL Server)
  7. cxf与struts2拦截器冲突的解决方案
  8. 在Orchard CMS Theme 用代码定义布局Widgets 配置
  9. Ubuntu linux 返回上一次访问的目录
  10. 数组方法 Array.prototype