博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HDU Common Subsequence(最长公共子序列)
阅读量:7090 次
发布时间:2019-06-28

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

Common Subsequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32838    Accepted Submission(s): 14875

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
 

 

Source
 

 

Recommend
Ignatius   |   We have carefully selected several similar problems for you:          
最长公共子序列问题,简单的动态规划
1处纵轴比到f横轴比到第二个b,从前面序列看,自然为3,和上一位f对f相等
2处横轴比到b,纵轴比到最后一个c,从序列上看,自然与纵轴上一个f相等,因为比到此处的cb处最多也就为2了。
3处比到cc,加上上处bf自然为3
反正看表多看几个特殊值感受下吧,感觉哪里没有完全明白
#include 
#include
using namespace std;int ans[1005][1005];int main(){ char a[1005],b[1005]; int i,j; while(cin>>a>>b){ int len1=strlen(a); int len2=strlen(b); for(i=0;i<=len1;i++) ans[i][0]=0; for(j=0;j<=len2;j++) ans[0][j]=0; for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(a[i-1]==b[j-1]) { ans[i][j]=ans[i-1][j-1]+1; } else { ans[i][j]=ans[i-1][j]>=ans[i][j-1]?ans[i-1][j]:ans[i][j-1];//为什么是上和左都取,因为这个横纵轴坐标是相互的,可互换 } } } cout<
<
在计算最优解的过程中,可以用另外一个二维数组来表示每次选择,用c[i][j]=1表示result[i][j]是由result[i-1][j-1]得来的,用c[i][j]=2表示result[i][j]是由result[i-1][j]得来的,由c[i][j]=3表示result[i][j]是由result[i][j-1]得来的。
根据c数组的值,可以倒着从最后一步步推出每步的选择,进而确定出公共子序列中的元素。

 

转载于:https://www.cnblogs.com/zhangmingzhao/p/7256449.html

你可能感兴趣的文章
docker 添加基础命令
查看>>
arm7上搭建boa并进行测试cgi+html
查看>>
iptables/netfiles基本使用
查看>>
angularJS拍照
查看>>
HTML5接入与OC交互
查看>>
错误整理:No plugin found for prefix 'jetty' in the....
查看>>
端口号简介
查看>>
JCreator中不能引入servlet包的解决办法
查看>>
mysql root账户被删除
查看>>
将CentOS设置为用光盘做yum源
查看>>
终于用上了比较完美的lion 10.7.3
查看>>
【CentOS 7笔记47】,rsync文件同步工具#171205
查看>>
word2007设置标题自动编号
查看>>
Ubuntu添加自定义快捷方式
查看>>
mysql 基本操作
查看>>
我的友情链接
查看>>
Xcode 使用Git User Interface State 问题
查看>>
我在群硕实习的日子
查看>>
个人知识管理是职场必修课
查看>>
基于 Android NDK 的学习之旅----- C调用Java(附源码)
查看>>