[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

相关文章

C#实现高性能Excel百万数据导出优化实战指南

《C#实现高性能Excel百万数据导出优化实战指南》在日常工作中,Excel数据导出是一个常见的需求,然而,当数据量较大时,性能和内存问题往往会成为限制导出效率的瓶颈,下面我们看看C#如何结合EPPl... 目录一、技术方案核心对比二、各方案选型建议三、性能对比数据四、核心代码实现1. MiniExcel

在React聊天应用中实现图片上传功能

《在React聊天应用中实现图片上传功能》在现代聊天应用中,除了文字和表情,图片分享也是一个重要的功能,本文将详细介绍如何在基于React的聊天应用中实现图片上传和预览功能,感兴趣的小伙伴跟着小编一起... 目录技术栈实现步骤1. 消息组件改造2. 图片预览组件3. 聊天输入组件改造功能特点使用说明注意事项

VSCode中配置node.js的实现示例

《VSCode中配置node.js的实现示例》本文主要介绍了VSCode中配置node.js的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一.node.js下载安装教程二.配置npm三.配置环境变量四.VSCode配置五.心得一.no

debian12安装docker的实现步骤

《debian12安装docker的实现步骤》本文主要介绍了debian12安装docker的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录步骤 1:更新你的系统步骤 2:安装依赖项步骤 3:添加 docker 的官方 GPG 密钥步骤

基于Redis实现附近商铺查询功能

《基于Redis实现附近商铺查询功能》:本文主要介绍基于Redis实现-附近商铺查询功能,这个功能将使用到Redis中的GEO这种数据结构来实现,需要的朋友可以参考下... 目录基于Redis实现-附近查询1.GEO相关命令2.使用GEO来实现以下功能3.使用Java实现简China编程单的附近商铺查询4.Red

使用Python实现实时金价监控并自动提醒功能

《使用Python实现实时金价监控并自动提醒功能》在日常投资中,很多朋友喜欢在一些平台买点黄金,低买高卖赚点小差价,但黄金价格实时波动频繁,总是盯着手机太累了,于是我用Python写了一个实时金价监控... 目录工具能干啥?手把手教你用1、先装好这些"食材"2、代码实现讲解1. 用户输入参数2. 设置无头浏

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I

Python实现剪贴板历史管理器

《Python实现剪贴板历史管理器》在日常工作和编程中,剪贴板是我们使用最频繁的功能之一,本文将介绍如何使用Python和PyQt5开发一个功能强大的剪贴板历史管理器,感兴趣的可以了解下... 目录一、概述:为什么需要剪贴板历史管理二、功能特性全解析2.1 核心功能2.2 增强功能三、效果展示3.1 主界面

Springboot实现推荐系统的协同过滤算法

《Springboot实现推荐系统的协同过滤算法》协同过滤算法是一种在推荐系统中广泛使用的算法,用于预测用户对物品(如商品、电影、音乐等)的偏好,从而实现个性化推荐,下面给大家介绍Springboot... 目录前言基本原理 算法分类 计算方法应用场景 代码实现 前言协同过滤算法(Collaborativ

springboot实现配置文件关键信息加解密

《springboot实现配置文件关键信息加解密》在项目配置文件中常常会配置如数据库连接信息,redis连接信息等,连接密码明文配置在配置文件中会很不安全,所以本文就来聊聊如何使用springboot... 目录前言方案实践1、第一种方案2、第二种方案前言在项目配置文件中常常会配置如数据库连接信息、Red