Cod sursa(job #2371250)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 6 martie 2019 16:55:45
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 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 int INF = 2e9;

struct Data {
    int node, 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<int> 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 ++)
        out << dp[i] << " ";

    return 0;
}