Cod sursa(job #2371302)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 6 martie 2019 17:05:35
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <map>
#include <stack>
#define ll long long

using namespace std;

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

const ll INF = 100000000000;

struct Data {
    int node;
    ll cost;

    bool operator< (const Data &other) const {
        if(cost == other.cost)
            return node < other.node;
        return cost < other.cost;
    }
};

int main() {

    int n, m;
    in >> n >> m;
    vector<vector<Data>> g(n + 1);
    for(int i = 1; i <= m; i ++) {
        int a, b, c;
        in >> a >> b >> c;
        g[a].push_back({b, c});
    }

    set<Data> s;
    s.insert({1, 0});
    vector<ll> dp(n + 1, INF);
    dp[1] = 0;

    while(s.size()) {
        auto from = *s.begin();
        s.erase(from);

        for(auto it : g[from.node]) {
            if(dp[it.node] > from.cost + it.cost) {
                s.erase({it.node, dp[it.node]});

                dp[it.node] = from.cost + it.cost;
                s.insert({it.node, dp[it.node]});
            }
        }
    }

    for(int i = 2; i <= n; i ++) {
        if(dp[i] == INF)
            dp[i] = 0;
        out << dp[i] << " ";
    }

    return 0;
}