博客
关于我
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/

你可能感兴趣的文章
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>