Cod sursa(job #2379104)

Utilizator dan.ghitaDan Ghita dan.ghita Data 12 martie 2019 21:33:30
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
 
int n, m, a, b, c;
vector<vector<pair<int, int>>> edges;
vector<int> cost;
priority_queue<int, vector<int>, function<bool(int, int)>> pq([](int a, int b) { return cost[a] > cost[b]; });

int main()
{
    f >> n >> m;
    edges.resize(n + 1);
    cost.resize(n + 1, INT_MAX);
 
    while (m--)
        f >> a >> b >> c,
        edges[a].push_back({b, c});
 
    pq.push(1);
    cost[1] = 0;
 
    while (!pq.empty())
    {
        int x = pq.top();
        pq.pop();
 
        for (int i = 0; i < edges[x].size(); ++i)
            if (cost[edges[x][i].first] > cost[x] + edges[x][i].second)
                cost[edges[x][i].first] = cost[x] + edges[x][i].second,
                pq.push(edges[x][i].first);
    }
 
    for (int i = 2; i <= n; ++i)
        g << ((cost[i] < INT_MAX) ? cost[i] : 0) << ' ';
 
    return 0;
}