栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

阿良的python算法之路(dirjkstra单源最短路径)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

阿良的python算法之路(dirjkstra单源最短路径)

目录

【模板】单源最短路径

参考题解

【蓝桥真题】单源最短路径

参考题解:


【模板】单源最短路径

亲,题目链接请戳这里

参考题解
import heapq

# 输入
n, m, start = map(int, input().split())

# 初始化
inf = 2 ** 31 - 1
MAX_SIZE = n + 10

# 建图
graph = {x: [] for x in range(1, n + 1)}
for _ in range(m):
    u, v, w = map(int, input().split())
    graph[u].append((v,w))

# 核心代码
def dirjkstra():
    # 各节点到start的最短距离
    dirs = [inf] * MAX_SIZE
    dirs[start] = 0

    # 已用节点,比set还快20%
    seen = [False] * MAX_SIZE

    pq = []
    heapq.heappush(pq, (0, start))

    # BFS
    while pq:
        # 获取
        _, now_node = heapq.heappop(pq)
        
        # 该节点是否用过
        if seen[now_node]:
            continue
        else:
            seen[now_node] = True

        # 找到邻接节点
        nodeList = graph[now_node]
        for sub_node, sub_dist in nodeList:
            t = dirs[now_node] + sub_dist
            if t < dirs[sub_node]:
                dirs[sub_node] = t
                # 如果该邻接节点没有访问过才把该最短边加进去
                if not seen[sub_node]:
                    heapq.heappush(pq, (t, sub_node))
                
    return dirs

answer = dirjkstra()

print(" ".join(map(str, answer[1:n+1])))

【蓝桥真题】单源最短路径

参考题解:(答案:10266837)
import heapq

def gcd(a, b):
    if a < b:
        a, b = b, a

    if a % b == 0:
        return b
    else :
        return gcd(b, a%b)

def lcm(a, b):
    return int(a * b / gcd(a, b))

n = 2021
inf = 2 ** 31 - 1
MAX_SIZE = n + 10

def init_graph():
    graph = {x: [] for x in range(1, n + 1)}
    for i in range(1, 2022):
        for j in range(1, 2022):
            if abs(i-j) <= 21:
                if i == j :
                    continue
                else:
                    graph[i].append([j, lcm(i, j)])

    return graph


graph = init_graph()
def dirjkstra(start):
    dirs = [inf] * MAX_SIZE
    dirs[start] = 0

    seen = [False] * MAX_SIZE

    pq = []
    heapq.heappush(pq, (0, start))

    while pq:
        _, now_node = heapq.heappop(pq)
        
        if seen[now_node]:
            continue
        else:
            seen[now_node] = True

        edgeList = graph[now_node]
        for sub_node, sub_dist in edgeList:
            t = dirs[now_node] + sub_dist
            if t < dirs[sub_node]:
                dirs[sub_node] = t

                if not seen[sub_node]:
                    heapq.heappush(pq, (t, sub_node))
                    
    return dirs

dirs = dirjkstra(1)
print(dirs[2021])
# 10266837

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/360286.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号