Cod sursa(job #2437992)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 10 iulie 2019 21:15:57
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int inf = 0x3f3f3f3f;

struct heap{
    int nod, cost;
    heap(int n, int c) : nod(n), cost(c) {}
    bool operator < (const heap &other) const {
        return cost > other.cost;
    }
};

priority_queue <heap> q;
vector <pair <int, int>> g[50005];
int d[50005];
bool use[50005];

int main()
{
    int n, m;
    fin >> n >> m;
    while (m--){
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b, c));
    }
    memset(d, inf, sizeof d);
    q.emplace(1, 0);
    d[1] = 0;
    while (!q.empty()){
        int nod = q.top().nod, cost = q.top().cost;
        q.pop();
        if (cost == d[nod]){
            for (auto i : g[nod]){
                int dist = d[nod] + i.second;
                if (dist < d[i.first]){
                    d[i.first] = dist;
                    q.emplace(i.first, d[i.first]);
                }
            }
        }
    }
    for (int i = 2; i <= n; i++){
        if (d[i] == inf)
            fout << 0;
        else
            fout << d[i];
        fout << ' ';
    }
    fout << '\n';
    return 0;
}