Pagini recente » Cod sursa (job #1067822) | Cod sursa (job #1411822) | Cod sursa (job #123117) | Cod sursa (job #2507618) | Cod sursa (job #2645218)
import heapq
def read_input(edges):
""" Read the input from the file and return it. """
with open("dijkstra.in") as file:
n, m = [int(x) for x in next(file).split()]
for i in range(n+1):
edges.append([])
for line in file:
nums = line.split()
edges[int(nums[0])].append((int(nums[1]),int(nums[2])))
def calculate_distances(graph, startVertex):
dist = [float("infinity") for i in range(n+1)]
dist[startVertex] = 0
priorityQ = [(0, startVertex)]
while len(priorityQ):
currentDistance, currentVertex = heapq.heappop(priorityQ)
if currentDistance > dist[currentVertex]:
continue
for neighbour, weight in graph[currentVertex]:
distance = currentDistance + weight
if distance < dist[neighbour]:
dist[neighbour] = distance
heapq.heappush(priorityQ, (distance, neighbour))
with open("dijkstra.out","w") as file:
for i in range(2, n+1):
if dist[i] != float("infinity"):
file.write("{} ".format(dist[i]))
else:
file.write("0 ")
# for i in range(2,n+1):
# print(dist[i],end=' ')
edges = []
read_input(edges)
startNode = 1
calculate_distances(edges, startNode)