Cod sursa(job #2138460)

Utilizator danyvsDan Castan danyvs Data 21 februarie 2018 17:41:57
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 50005;
const int INF = 0x3f3f3f3f;

int n, m;
vector<pair<int, int>> G[NMAX];
vector<int> dist(NMAX, INF);

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; ++ i) {
        int from, to, cost;
        fin >> from >> to >> cost;
        G[from].push_back(make_pair(to, cost));
    }
}

void dijkstra() {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap;
    dist[1] = 0;
    heap.push(make_pair(0, 1));
    while (!heap.empty()) {
        int currNode = heap.top().second;
        int d = heap.top().first;
        heap.pop();
        if (dist[currNode] <= d)
            for (auto it : G[currNode]) {
                int node = it.first;
                int cost = it.second;
                if (dist[node] > dist[currNode] + cost) {
                    dist[node] = dist[currNode] + cost;
                    heap.push(make_pair(dist[node], node));
                }
            }
    }
}

void print() {
    for (int i = 2; i <= n; ++ i)
        fout << (dist[i] != INF ? dist[i] : 0) << " ";
    fout << "\n";
}

int main() {
    read();
    fin.close();
    dijkstra();
    print();
    fout.close();
    return 0;
}