Cod sursa(job #3338164)

Utilizator iulianarsenoiuArsenoiu Iulian iulianarsenoiu Data 1 februarie 2026 03:29:25
Problema Algoritmul lui Dijkstra Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 1.1 kb
import numpy
import heapq

oo = 2e9

def Dijkstra(G, s):
    global oo
    n = len(G)
    d = []
    h = []
    sel = []
    for i in range(0, n):
        d.append(oo)
        sel.append(False)
    heapq.heappush(h, (0, s))
    d[s] = 0
    while len(h) > 0:
        while(len(h) > 0):
            top = heapq.heappop(h)
            if(sel[top[1]] == False):
                heapq.heappush(h, top)
                break
        if(len(h) == 0):
            break
        top = heapq.heappop(h)
        nod = top[1]
        sel[nod] = True
        for it in G[nod]:
            if(d[nod] + it[1] < d[it[0]]):
                d[it[0]] = d[nod] + it[1]
                heapq.heappush(h, (d[it[0]], it[0]))
    return d


fin = open("dijkstra.in", "r")
fout = open("dijkstra.out", "w")

[n, m] = map(int, fin.readline().split())
G = []
for i in range(0, n):
    G.append([])
for i in range(0, m):
    [x, y, c] = map(int, fin.readline().split())
    x = x - 1
    y = y - 1
    G[x].append((y, c))
    G[y].append((x, c))

rez = Dijkstra(G, 0)

out = ""
for i in range(1, len(rez)):
    out += str(rez[i]) + " "

fout.write(out)