Cod sursa(job #2657839)

Utilizator raducostacheRadu Costache raducostache Data 12 octombrie 2020 12:19:49
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <queue>

#define NMAX 50005
#define INF 1000000005

using namespace std;

int n, m;
int cost[NMAX];
priority_queue <int> q;
vector <pair <int, int>> v[NMAX];

inline void read();
inline void solve();
inline void print();

int main() {
    read();
    solve();
    print();
    return 0;
}

inline void read() {
    ifstream f("dijkstra.in");
    f >> n >> m;
    while (m--) {
        int x, y, c;
        f >> x >> y >> c;
        v[x].push_back({y, c});
    }
}

inline void solve() {
    priority_queue <pair <int, int>, vector <pair<int, int> >, greater <pair <int, int> > > q;
    for (int i = 2; i <= n; ++i) {
        cost[i] = INF;
    }
    q.push({0, 1});
    while (!q.empty()) {
        int node = q.top().second;
        int curc = q.top().first;

        q.pop();
        if (curc > cost[node])
            continue;
        for (auto it:v[node])
            if (cost[node] + it.second < cost[it.first]) {
                cost[it.first] = cost[node] + it.second;
                q.emplace(cost[it.first], it.first);
            }
    }

}

inline void print() {
    ofstream g("dijkstra.out");
    for (int i = 2; i <= n; ++i) {
        g << cost[i] << ' ';
    }
    g << '\n';
}