Cod sursa(job #2656307)

Utilizator raducostacheRadu Costache raducostache Data 7 octombrie 2020 14:07:41
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

#define NMAX 50005
#define INF 1000000005

using namespace std;

int n, m, cost[NMAX];
struct comp{
    bool operator()(int x, int y) {
        return cost[x] > cost[y];
    }
};


multiset <int, comp> q;
vector <pair<int, int>> v[NMAX];

void dijkstra(int);

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() {

    for (int i = 1; i <= n; ++i)
        cost[i] = INF;
    dijkstra(1);
}

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

void dijkstra(int start) {
    cost[start] = 0;
    for (int i = 1; i <= n; ++i) {
        q.insert(i);
    }
    while (!q.empty()) {
        int x = *q.begin();
        q.erase(q.begin ());
        for (auto it:v[x]) {
            if (cost[x] + it.second < cost[it.first]) {
                cost[it.first] = cost[x] + it.second;
                q.erase(it.first);
                q.insert(it.first);
            }
        }

    }
}