Cod sursa(job #1921111)

Utilizator BaweeLazar Vlad Bawee Data 10 martie 2017 11:24:40
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

int d[50001];
int n, m, x, y, c;
const int INF = 1 << 30;

vector < int > heap;
vector < pair < int , int > > G[50001];

bool cmp(const int &h1, const int &h2) {
    return d[h1] > d[h2];
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i) {
        f >> x >> y >> c;
        G[x].push_back({y , c});
        G[y].push_back({x , c});
    }

    for(int i = 1; i <= n; ++i)
        d[i] = INF;

    d[1] = 0;
    heap.push_back(1);
    make_heap(heap.begin(), heap.end(), cmp);
    while(heap.size()) {
        int node = heap.front();
        pop_heap(heap.begin(), heap.end(), cmp);
        heap.pop_back();

        for(const auto &nextNode : G[node]) {
            if(d[nextNode.first] > d[node] + nextNode.second) {
                d[nextNode.first] = d[node] + nextNode.second;
                heap.push_back(nextNode.first);
                push_heap(heap.begin(), heap.end(), cmp);
            }
        }
    }

    for(int i = 2; i <= n; ++i) {
        if(d[i] == INF) g << "0 ";
        else g << d[i] << " ";
    }
    return 0;
}