【问题描述】Prim算法解决的是带权重的无向图上连接所有顶点的耗费最小的生成树。Q使用最小堆数据结构。
【输入形式】在屏幕上输入顶点个数和连接顶点间的边的权矩阵。
【输出形式】顺序输出按照贪心选择得到的各顶点序号,及该顶点的前驱顶点序号,及路径长度。
【样例1输入】
8
0 15 7 0 0 0 0 10
15 0 0 0 0 0 0 0
7 0 0 9 12 5 0 0
0 0 9 0 0 0 0 0
0 0 12 0 0 6 0 0
0 0 5 0 6 0 14 8
0 0 0 0 0 14 0 3
10 0 0 0 0 8 3 0
【样例1输出】
3 1 7
6 3 5
5 6 6
8 6 8
7 8 3
4 3 9
2 1 15
【样例说明】
输入:顶点个数为8。连接顶点间边的权矩阵大小为8行8列,位置[i,j]上元素值表示第i个顶点到第j个顶点的距离,0表示两个顶点间没有边连接。
输出:顺序输出按照贪心选择得到的各顶点序号,及该顶点的前驱顶点序号,及路径长度。
【评分标准】根据输入得到准确的输出。
import heapq
import numpy as np
class VertexNode(object):
def __init__(self, index=None, key=np.inf, previous=None):
self.index = index
self.key = key
self.previous = previous
def __repr__(self):
pass
def __lt__(self, other):
return self.key < other.key
class Heap: # 使用包装类堆heapq包装,让heapq优先队列中的元素成为对象
def __init__(self):
self._queue = []
def push(self, item):
heapq.heappush(self._queue, item)
def pop(self):
if self._queue:
return heapq.heappop(self._queue)
else:
return None
def heapify(self):
heapq.heapify(self._queue)
@property
def queue(self):
return self._queue
def prime(b, c):
num = 0
Q = Heap()
# 将节点放到优先队列中
for i in c:
Q.push(i)
while Q.queue:
# 取出最小节点
u = Q.pop()
# 在优先队列查找
for q in Q.queue:
v = q
if 0 < b[u.index, v.index] < v.key:
v.key = b[u.index, v.index]
v.previous = u.index+1
Q.heapify()
num += 1
if num != 1:
show(u)
def show(u):
u.index = u.index+1
print(f"{u.index} {u.previous} {u.key}")
def main():
n = int(input())
a = []
c = []
for i in range(n):
a.append(list(map(int, input().rstrip().split())))
b = np.array(a).reshape(n, n)
node = VertexNode(0, 0, None)
c.append(node)
for i in range(1, n):
node = VertexNode(i, np.inf, None)
c.append(node)
prime(b, c)
if __name__ == '__main__':
main()
"""
8
0 15 7 0 0 0 0 10
15 0 0 0 0 0 0 0
7 0 0 9 12 5 0 0
0 0 9 0 0 0 0 0
0 0 12 0 0 6 0 0
0 0 5 0 6 0 14 8
0 0 0 0 0 14 0 3
10 0 0 0 0 8 3 0
"""