博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UVA 10405 Longest Common Subsequence (动态规划 LCS)
阅读量:7070 次
发布时间:2019-06-28

本文共 1930 字,大约阅读时间需要 6 分钟。

Longest Common Subsequence

Sequence 1:                

Sequence 2:                

Given two sequences of characters, print the length of the longest common subsequence of both sequences. For example, the longest common subsequence of the following two sequences:

abcdghaedfhr
is 
adh of length 3.

Input consists of pairs of lines. The first line of a pair contains the first string and the second line contains the second string. Each string is on a separate line and consists of at most 1,000 characters

For each subsequent pair of input lines, output a line containing one integer number which satisfies the criteria stated above.

Sample input

a1b2c3d4ezz1yy2xx3ww4vvabcdghaedfhrabcdefghijklmnopqrstuvwxyza0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0abcdefghijklmnzyxwvutsrqpoopqrstuvwxyzabcdefghijklmn

Output for the sample input

432614 题目大意:求最长公共子序列 设d[i][j]为A1,A2...Ai和B1,B2...Bj的LCS长度,则的d[i][j]=max{d[i-1][j],d[i][j-1]},如果A[i]=B[j],d[i][j]=max{d[i][j],d[i-1][j-1]+1},边界条件是最外层为0 时间复杂度为O(nm),n、m分别为序列A、B的长度
View Code
1 # include
2 # include
3 # define maxn 1005 //这样定义max函数,是不是就不用考虑a,b的类型了 4 # define max(a,b) a>b?a:b 5 int dp[maxn][maxn]; 6 char a[maxn],b[maxn]; 7 int main(){ 8 int lena,lenb,i,j; 9 while(gets(a)&&gets(b)){ //题目中这里不能用scanf,只能用gets输入10 lena=strlen(a);11 lenb=strlen(b);12 13 for(i=0;i<=lena;i++)14 for(j=0;j<=lenb;j++)15 dp[i][j] = 0;16 17 for(i=1;i<=lena;i++)18 {19 for(j=1;j<=lenb;j++)20 {21 dp[i][j] = max(dp[i-1][j],dp[i][j-1]); 22 if(a[i-1]==b[j-1]) 23 dp[i][j] = max(dp[i][j] , dp[i-1][j-1] + 1);24 } 25 } 26 27 printf("%d\n",dp[lena][lenb]);28 }29 return 0;30 }

 

 

转载地址:http://slhll.baihongyu.com/

你可能感兴趣的文章
Mongodb学习(安装篇): 在centos下的安装
查看>>
python "re" 模块
查看>>
代码实现SQL Server动态行转列,不用存储过程
查看>>
最新android adt 21.1.0
查看>>
servlet中避免405错误的产生
查看>>
Git的checkout, reset, revert
查看>>
取余递归
查看>>
Java金钱小写转大写
查看>>
林小宅的点名册
查看>>
常用算法Java实现之直接插入排序
查看>>
X5功能目录排序
查看>>
《第一行代码》书籍阅读笔记
查看>>
java基础知识点复习
查看>>
[Hive_add_10] Hive 的 serde (序列化 & 反序列化) 操作
查看>>
7月18日实习日志
查看>>
python面向对象之类成员修饰符
查看>>
Linux命令大全之基本命令
查看>>
HDU2048 神、上帝以及老天爷
查看>>
Android开发指南(35) —— Toast Notifications
查看>>
【Andorid X 项目笔记】禁用ListView的Fling功能(1)
查看>>