Cod sursa(job #2379091)

Utilizator dan.ghitaDan Ghita dan.ghita Data 12 martie 2019 21:16:46
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n, m, a, b, c;
vector<pair<int, int>> edges[50003];
int cost[50003];
priority_queue<int, vector<int>, function<bool(int, int)>> pq([&](int a, int b) { return cost[a] > cost[b]; });

int main()
{
    f >> n >> m;
    
    while (m--)
        f >> a >> b >> c,
        edges[a].push_back({b, c});

    for (int i = 1; i <= n; ++i)
        cost[i] = INT_MAX;

    pq.push(1);
    cost[1] = 0;

    while (!pq.empty())
    {
        int x = pq.top();
        pq.pop();

        for (auto const& p : edges[x])
            if (cost[p.first] > cost[x] + p.second)
                cost[p.first] = cost[x] + p.second,
                pq.push(p.first);
    }

    for (int i = 2; i <= n; ++i)
        g << ((cost[i] < INT_MAX) ? cost[i] : 0) << ' ';

    return 0;
}