[Python3]Bellman-Ford的实现及Yen式优化

2023-10-07 20:50

本文主要是介绍[Python3]Bellman-Ford的实现及Yen式优化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原理分析见本人Github:

https://github.com/youhengchan/Yen-Bellman-Ford/blob/master/group2_ppt_yen.pdf

测试数据:

原始算法:

伪代码:

实现:

import timegraph_size = 10
counter = 0class Edge:def __init__(self, u, v, w):self.u = uself.v = vself.w = wdef recursive_print(dis, pre):global graph_sizedef print_helper(index, destination):if pre[index] == index:print("Route : {} -> ".format(index), end="")returnprint_helper(pre[index], destination)if index == destination:print("{} Distance = {}".format(destination, dis[destination]), end="")else:print("{} -> ".format(index), end="")for i in range(graph_size):if pre[i] == i:print("Route : {} Distance = 0".format(i), end="")else:print_helper(i, i)print("")def bellman_ford(edges, source):global graph_size, counterbegin = time.perf_counter()dis = []  # distance from source to the nodepre = []  # predecessor of nodeerror = Falsefor i in range(graph_size):dis.append(float('inf'))pre.append(i)dis[source] = 0# Initialize the graphfor i in range(graph_size - 1):   # |V| - 1 timescounter += 1# change = Falsefor edge in edges:if dis[edge.u] != float("inf") and dis[edge.v] > (dis[edge.u] + edge.w):dis[edge.v] = dis[edge.u] + edge.wpre[edge.v] = edge.u# change = True# if not change:#     break# check for the negative-weight cyclefor edge in edges:if (dis[edge.u] + edge.w) < dis[edge.v]:print("dis[{}] ({}) < dis[{}] ({}) + {}".format(edge.u, dis[edge.u], edge.v, dis[edge.v], edge.w))error = Trueend = time.perf_counter()return error, dis, pre, end-begindef main():global counteredges = []edges.append(Edge(0, 9, 9))edges.append(Edge(0, 2, 3))edges.append(Edge(0, 5, 5))edges.append(Edge(7, 9, 2))edges.append(Edge(7, 3, 0))edges.append(Edge(2, 7, 1))edges.append(Edge(9, 4, 3))edges.append(Edge(3, 4, 2))edges.append(Edge(3, 8, 1))edges.append(Edge(8, 2, 8))edges.append(Edge(8, 6, 2))edges.append(Edge(4, 8, -8))edges.append(Edge(6, 1, 0))edges.append(Edge(5, 1, 2))edges.append(Edge(1, 4, 9))err, dis, pre, time_consumption = bellman_ford(edges, 0)if err:print("Negative-weight cycle exist")else:print("Time consumption = ", time_consumption)recursive_print(dis, pre)print("Counter = ", counter)if __name__ == "__main__":main()

运行结果:

Yen氏优化:

伪代码:

实现:

import time
graph_size = 10
counter = 0class Edge:def __init__(self, u, v, w):self.u = uself.v = vself.w = wdef recursive_print(dis, pre):global graph_sizedef print_helper(index, destination):if pre[index] == index:print("Route : {} -> ".format(index), end="")returnprint_helper(pre[index], destination)if index == destination:print("{} Distance = {}".format(destination, dis[destination]), end="")else:print("{} -> ".format(index), end="")for i in range(graph_size):if pre[i] == i:print("Route : {} Distance = 0".format(i), end="")else:print_helper(i, i)print("")def yen_bellman_ford(edges, edge_plus, edge_minus, source):begin = time.perf_counter()global graph_size, counterdis = []  # distance from source to the nodepre = []  # predecessor of nodeerror = Falsefor i in range(graph_size):dis.append(float('inf'))pre.append(i)dis[source] = 0# Initialize the graphfor i in range(graph_size - 1):   # |V| - 1 timescounter += 1change = Falsefor edge in edge_plus:if dis[edge.u] != float("inf") and dis[edge.v] > (dis[edge.u] + edge.w):dis[edge.v] = dis[edge.u] + edge.wpre[edge.v] = edge.uchange = Truefor edge in edge_minus:if dis[edge.u] != float("inf") and dis[edge.v] > (dis[edge.u] + edge.w):dis[edge.v] = dis[edge.u] + edge.wpre[edge.v] = edge.uchange = Trueif not change:break# check for the negative-weight cyclefor edge in edges:if (dis[edge.u] + edge.w) < dis[edge.v]:print("dis[{}] ({}) < dis[{}] ({}) + {}".format(edge.u, dis[edge.u], edge.v, dis[edge.v], edge.w))error = Trueend = time.perf_counter()return error, dis, pre, end-begindef main():edges = []edge_plus = []edge_minus = []edge_plus.append(Edge(0, 2, 3))edge_plus.append(Edge(0, 5, 5))edge_plus.append(Edge(0, 9, 9))edge_plus.append(Edge(1, 4, 9))edge_plus.append(Edge(2, 7, 1))edge_plus.append(Edge(3, 4, 2))edge_plus.append(Edge(3, 8, 1))edge_plus.append(Edge(4, 5, 0))edge_plus.append(Edge(4, 8, -8))edge_plus.append(Edge(7, 9, 2))edge_minus.append(Edge(9, 4, 3))edge_minus.append(Edge(8, 6, 2))edge_minus.append(Edge(8, 2, 8))edge_minus.append(Edge(7, 3, 0))edge_minus.append(Edge(6, 1, 0))edge_minus.append(Edge(5, 1, 2))edges.extend(edge_minus)edges.extend(edge_plus)err, dis, pre, time_consumption = yen_bellman_ford(edges, edge_plus, edge_minus, 0)if err:print("Negative-weight cycle exist")else:print("Time consumption = ", time_consumption)recursive_print(dis, pre)print("Counter = ", counter)if __name__ == "__main__":main()

运行结果:

这篇关于[Python3]Bellman-Ford的实现及Yen式优化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/160366

相关文章

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方