Pagini recente » Cod sursa (job #2036207) | Cod sursa (job #2380569) | Cod sursa (job #402967) | Cod sursa (job #2064156) | Cod sursa (job #2645226)
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.readlines():
nums = line.split()
edges[int(nums[0])].append((int(nums[1]),int(nums[2])))
def calculate_distances():
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):
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=' ')
graph = []
read_input(graph)
n=len(graph)
startVertex = 1
calculate_distances()