Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2601 from SusanAIFF/master
Browse files Browse the repository at this point in the history
更新了prim寻宝的python写法
  • Loading branch information
youngyangyang04 authored Jul 9, 2024
2 parents 0828601 + 45ad945 commit b7eb403
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions problems/kamacoder/0053.寻宝-prim.md
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,40 @@ int main() {
### Java

### Python
```python
# 接收输入
v, e = list(map(int, input().strip().split()))
# 按照常规的邻接矩阵存储图信息,不可达的初始化为10001
graph = [[10001] * (v+1) for _ in range(v+1)]
for _ in range(e):
x, y, w = list(map(int, input().strip().split()))
graph[x][y] = w
graph[y][x] = w

# 定义加入生成树的标记数组和未加入生成树的最近距离
visited = [False] * (v + 1)
minDist = [10001] * (v + 1)

# 循环 n - 1 次,建立 n - 1 条边
# 从节点视角来看:每次选中一个节点加入树,更新剩余的节点到树的最短距离,
# 这一步其实蕴含了确定下一条选取的边,计入总路程 ans 的计算
for _ in range(1, v + 1):
min_val = 10002
cur = -1
for j in range(1, v + 1):
if visited[j] == False and minDist[j] < min_val:
cur = j
min_val = minDist[j]
visited[cur] = True
for j in range(1, v + 1):
if visited[j] == False and minDist[j] > graph[cur][j]:
minDist[j] = graph[cur][j]

ans = 0
for i in range(2, v + 1):
ans += minDist[i]
print(ans)
```

### Go

Expand Down

0 comments on commit b7eb403

Please sign in to comment.