Pagini recente » Cod sursa (job #2600857) | Cod sursa (job #2633030) | Cod sursa (job #806896) | Cod sursa (job #2301142) | Cod sursa (job #2645293)
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]) & 0xffffffff].append((int(nums[1]) & 0xffffffff,int(nums[2]) & 0xffffffff))
def calculate_distances():
dist = [1000000000 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] != 1000000000:
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()