在此基础上,将有向图G替换示。请编写程为加权有向图P,如下图 所序进行图的构建与相关运算,实现以下功能: (1)输入图P的顶点序列和边 (2)建立加权有向图P的邻接矩阵,并输出。 (3)建立加权有向图P的邻接表,并输出。 (4)计算每个顶点出发的边的权重之和sum,并输出 sum最大的顶点名称和sum的值。
时间: 2024-02-26 21:57:36 浏览: 64
好的,我可以帮你实现这个功能。以下是实现该功能的 Python 代码:
```python
class Vertex:
def __init__(self, name):
self.name = name
self.adjacent = {}
self.sum = 0
def add_neighbor(self, neighbor, weight):
self.adjacent[neighbor] = weight
def get_connections(self):
return self.adjacent.keys()
def get_weight(self, neighbor):
return self.adjacent[neighbor]
def get_name(self):
return self.name
def get_sum(self):
return self.sum
def set_sum(self, value):
self.sum = value
def __str__(self):
return self.name + ' adjacent: ' + str([x.name for x in self.adjacent])
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex):
self.vertices[vertex.get_name()] = vertex
def get_vertex(self, name):
if name in self.vertices:
return self.vertices[name]
else:
return None
def add_edge(self, frm, to, weight):
if frm not in self.vertices:
self.add_vertex(Vertex(frm))
if to not in self.vertices:
self.add_vertex(Vertex(to))
self.vertices[frm].add_neighbor(self.vertices[to], weight)
def get_vertices(self):
return self.vertices.keys()
def build_adj_matrix(self):
size = len(self.vertices)
matrix = [[0] * size for i in range(size)]
vertex_list = list(self.vertices.values())
vertex_index = {}
for i in range(size):
vertex_index[vertex_list[i]] = i
for i in range(size):
vertex = vertex_list[i]
for neighbor in vertex.get_connections():
j = vertex_index[neighbor]
matrix[i][j] = vertex.get_weight(neighbor)
return matrix
def build_adj_list(self):
adj_list = {}
for vertex in self.vertices.values():
adj_list[vertex.get_name()] = []
for neighbor in vertex.get_connections():
adj_list[vertex.get_name()].append((neighbor.get_name(), vertex.get_weight(neighbor)))
return adj_list
def compute_sum(self):
max_sum = 0
max_vertex = None
for vertex in self.vertices.values():
total_weight = sum(vertex.adjacent.values())
vertex.set_sum(total_weight)
if total_weight > max_sum:
max_sum = total_weight
max_vertex = vertex.get_name()
return max_vertex, max_sum
```
这里定义了两个类 `Vertex` 和 `Graph`,其中 `Vertex` 表示图中的顶点,包含顶点名称、邻接表以及边权重之和等信息;`Graph` 表示加权有向图,包含顶点集合和一些常用的图操作,如添加顶点、添加边、构建邻接矩阵、构建邻接表和计算顶点出发的边的权重之和等。
你可以按照以下步骤使用该程序:
1. 创建一个 `Graph` 对象,然后逐步添加顶点和边,如下所示:
```python
g = Graph()
g.add_vertex(Vertex('A'))
g.add_vertex(Vertex('B'))
g.add_vertex(Vertex('C'))
g.add_vertex(Vertex('D'))
g.add_edge('A', 'B', 2)
g.add_edge('A', 'C', 3)
g.add_edge('B', 'C', 1)
g.add_edge('B', 'D', 4)
g.add_edge('C', 'D', 2)
```
2. 构建邻接矩阵和邻接表,分别调用 `build_adj_matrix` 和 `build_adj_list` 方法即可:
```python
adj_matrix = g.build_adj_matrix()
adj_list = g.build_adj_list()
```
3. 计算每个顶点出发的边的权重之和 sum,并输出 sum 最大的顶点名称和 sum 的值,调用 `compute_sum` 方法即可:
```python
max_vertex, max_sum = g.compute_sum()
print('Max sum is %d for vertex %s' % (max_sum, max_vertex))
```
这样就完成了加权有向图的构建和相关运算了。
阅读全文