Cod sursa(job #3344304)

Utilizator Alex283810Mocan Alexandru Vali Alex283810 Data 1 martie 2026 20:15:36
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

std::ifstream fin("dijkstra.in");
std::ofstream fout("dijkstra.out");

struct node
{
    int nod;
    int cost;

    inline bool operator > (const node& other) const
    {
        return cost < other.cost;
    }
};

std::vector<std::vector<node>>graph;

int main()
{
    int n, m;
    fin >> n >> m;
    graph.resize(n + 1);
    std::vector<int> dist(n + 1, INT_MAX);
    for(int i = 1; i <= m; i++)
    {
        int a, b, cost;
        fin >> a >> b >> cost;
        graph[a].push_back({b, cost});
    }
    std::priority_queue<node, std::vector<node>, std::greater<node>>pq;
    pq.push({1, 0});
    while(!pq.empty())
    {
        auto curr = pq.top();
        pq.pop();

        int cost = curr.cost;
        int nod = curr.nod;

        for(auto leg : graph[nod])
        {
            int cost_leg = leg.cost;
            int neigh = leg.nod;

            if(dist[neigh] > cost + cost_leg)
            {
                dist[neigh] = cost + cost_leg;
                pq.push({neigh, cost + cost_leg});
            }
        }
    }
    for(int i = 2; i <= n; i++)
    {
        fout << dist[i] << ' ';
    }
}