CCF-201609-4-交通规划

匿名 (未验证) 提交于 2019-12-02 22:59:29
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AivenZhong/article/details/84346205

题目意思是:求最短路径的同时还要保证这些路径的总权值最小
在两条总权值相等的路径中,经过结点最多的那个最好。你想想,如果我能从原来已有的结点上再加一条到达木雕。是不是好过从上一个结点再拉一条呢。
代码只要在原来的dijkstra算法上改一下就好了。新加一个存储到父结点的边权值,在每次更新最短路径的时候,看新的父结点的边值是否小于以前的,是就更改父结点和父结点边的权值。
python代码:

def dij(start, graph):     n = len(graph)     costs = [99999 for _ in range(n)]     parents = [-1 for _ in range(n)]     parents_costs = [99999 for _ in range(n)]     costs[start] = 0     visited = [False for _ in range(n)]     t = []     while len(t) < n:         # 每次从costs里找最短花销,把最短花销的结点加进t中         minCost = 99999         minNode = start         for i in range(len(costs)):             if not visited[i] and costs[i] < minCost:                 minNode = i                 minCost = costs[i]         t.append(minNode)         visited[minNode] = True          # 找这点的邻边(子结点不在t里面)         # 如果邻边的子结点的路径花销小于原来的花销,就更新花销和父结点         for edge in graph[minNode]:             if not visited[edge[0]] and edge[1] + minCost <= costs[edge[0]]:                 if edge[1] + minCost < costs[edge[0]]:                     costs[edge[0]] = edge[1] + minCost                     parents[edge[0]] = minNode                     parents_costs[edge[0]] = edge[1]                 elif edge[1] < parents_costs[edge[0]]:                     parents[edge[0]] = minNode                     parents_costs[edge[0]] = edge[1]     return costs, parents, parents_costs   n, m = map(int, input().split()) # 邻接表 graph = [[] for _ in range(n)] for i in range(m):     edge = list(map(int, input().split()))     graph[edge[0] - 1].append([edge[1] - 1, edge[2]])     graph[edge[1] - 1].append([edge[0] - 1, edge[2]])  costs, parents, parents_costs = dij(0, graph)  # 算总费用 total = 0 for i in range(1, len(parents_costs)):     total += parents_costs[i] print(parents) print(parents_costs) print(total) 
转载请标明出处:CCF-201609-4-交通规划
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!