Common Subsequence
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 34477   Accepted: 13631

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         abfcab
programming contest
abcd mnp

Sample Output

4
2
0

Source

 
题意:
求两个字符串的最长公共子序列(lcs)的长度。
思路:
金典问题,动态转移方程如下:
 if(i==||j==)
dp[i][j]=;
else if(x[i]==y[i])
dp[i][j]=dp[i-][j-]+;
else
dp[i][j]=max(dp[i-][j],dp[i][j-]);

代码如下:

 #include<iostream>
#include<string>
#include<cmath>
using namespace std;
const int MAX=;
int dp[MAX][MAX]={};
int max(int a,int b)
{
return a>b?a:b;
}
int main(int *argv,int *argc[])
{
int len1,len2,i,j;
string str1,str2; //有时在时间允许范围内,用cin读字符串比较方便
while(cin>>str1>>str2)
{
len1=str1.length();
len2=str2.length();
for(i=;i<=len1;i++)
{
for(j=;j<=len2;j++)
//转移方程
{
if(str1[i-]==str2[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. 【poj1740】 A New Stone Game
  2. 七、Java基础---------JDK安装与配置
  3. 试求由a,b,c三个字母组成的n位符号串中不出现aa图像的符号串的数目
  4. gulp初涉
  5. Java学习----Java数据类型
  6. kubuntu14.04以下vpn(vpnc)连接配置
  7. eclipse如何导入项目和文件
  8. Vue.js如何在一个页面调用另一个同级页面的方法
  9. 集成Struts2+Spring+Hibernate_两种方案
  10. ubuntu php 安装
  11. 菜鸟教程之工具使用(四)——借助JRebel使Tomcat支持热部署
  12. Confluence 6 为站点启用匿名用户访问
  13. struts2用到的jar有那些
  14. 基于Nginx反向代理及负载均衡
  15. Spring MVC @PathVariable注解
  16. [BZOJ2007][NOI2010]海拔(对偶图最短路)
  17. 笔记:C 编译过程
  18. pId的数据结构转children 数据结构(JS);
  19. java源码阅读StringBuilder
  20. python 常用系统参数

热门文章

  1. 第一章 EL表达式常见用法
  2. Android Studio体验(二)--创建项目和Genymotion试用
  3. 判断 iframe 是否加载完毕
  4. 俄罗斯水手 [C#] 对List&lt;T&gt;取交集、连集及差集
  5. leetcode 二分查找 Search in Rotated Sorted ArrayII
  6. Discuz常见小问题-如何修改导航栏
  7. linux python调试技巧
  8. Linux文件类型(学习笔记六)
  9. Java从零开始学十五(继承)
  10. secureCRT简单设置(学习笔记二)