BUAA离散数学第十章 图论 最短路径及关键通路 python解法
前言
离散数学尹宝林第三版 书上第十章10.1 10.3 的通用算法(python给出)
一、最短通路
题目描述
给定一个带权有向图,试求从顶点 s s s到 t t t的最短通路
输入
第一行四个由空格隔开的整数 n n n (顶点个数), m m m (边数), s s s (起点), t t t (终点)组成; 之后的 m m m 行,每行三个正整数 a a a , b b b , c c c ,表示一条从顶点 a a a 到顶点 b b b 长度为 c c c 的边。
输出
一共两行 第一行:路径,从源点到终点依次输出所经过得节点;第二行:一个整数,表示从 s s s 到 t t t 的最短路长度。数据保证仅一条通路。
解题思路
直接使用顶点和边的集合来建立图,用通常解法,即Bellman-Ford算法来求解最短路径,对所有边进行Relax操作,算法复杂度为 O ( V E ) O(VE) O(VE),下面给出代码。
代码
顶点
class GraphVertex:
def __init__(self, index):
self.index = index
self.d = float('inf')
self.pi = None
边
class GraphEdge:
def __init__(self, u, v, w):
self.e = (u, v)
self.w = w
图
class Graph:
def __init__(self, vertex_size, edge_size):
self._VertexSize = vertex_size
self._EdgeSize = edge_size
self._V = [GraphVertex(0)]
self._E = []
for __i in range(1, vertex_size + 1):
self._V.append(GraphVertex(__i))
def insert(self, __a, __b, __c):
self._E.append(GraphEdge(self._V[__a], self._V[__b], __c))
def get_vertex(self, node_index: int) -> GraphVertex:
return self._V[node_index]
@staticmethod
def