博客
关于我
C++:算法设计策略之动态规划法
阅读量:718 次
发布时间:2019-03-21

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

最长公共子序列问题

题目描述

给定两个序列X={x₁, x₂, …, xₘ}和Y={y₁, y₂, …, yₙ},目标是找出X和Y的最长公共子序列(LCS)。

输入

输入分为以下几行:

  • 第一行:输入序列X;
  • 第二行:输入序列Y。

注意:输入序列后面添加一个空格字符,以便处理特殊情况。

输出

输出X和Y的最长公共子序列的长度。

实验代码

以下是实现最长公共子序列问题的代码:

#include 
#include
#include
using namespace std;string a, b;int N = 1001;int r[N][N] = {0};int LCS(int la, int lb) { int i, j; // 初始化边界行列 for (i = 1; i <= la; ++i) r[i][0] = 0; for (j = 1; j <= lb; ++j) r[0][j] = 0; //Fill DP table for (i = 1; i <= la; ++i) { for (j = 1; j <= lb; ++j) { if (a[i] == b[j]) { r[i][j] = r[i-1][j-1] + 1; } else { if (r[i-1][j] >= r[i][j-1]) { r[i][j] = r[i-1][j]; } else { r[i][j] = r[i][j-1]; } } } } return r[la][lb];}int main() { // 读取输入 cin >> a >> b; int la = a.length(), lb = b.length(); // 方便处理边界情况 a += ' '; b += ' '; int LCS_length = LCS(la, lb); cout << LCS_length; return 0;}

结论

通过上述方法,我们能够高效地解决最长公共子序列问题。该算法基于动态规划原理,时间复杂度为O(NM),空间复杂度为O(NM)(其中N和M分别为两个序列的长度)。此外,为了确保程序的鲁棒性,代码中增加了对边界情况的处理。

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

你可能感兴趣的文章
tableviewcell 中使用autolayout自适应高度
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>