Cod sursa(job #2500357)

Utilizator topala.andreiTopala Andrei topala.andrei Data 27 noiembrie 2019 19:26:12
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 50001;
const int inf = 1 << 30;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int d[maxn];
int n,m;
struct Nod
{
    int y, cost;
    Nod() {
        y = 0;
        cost = 0;
    }
    inline Nod(int _y, int _cost) {
        y = _y;
        cost = _cost;
    }
    inline bool operator < (const Nod &x) const {
        return cost > x.cost;
    }
};
vector <Nod> v[maxn];
priority_queue <Nod>c;
void citire() {
    f>>n>>m;
 
    int x, y, cost;
    for (int i = 1; i <= m; ++i ) {
        f >> x >> y >> cost;
        v[x].push_back(Nod(y, cost));
    }
}
void dijkstra_heap(int x)
{
    for ( int i = 1; i <= n; ++i )
    {
        d[i] = inf;
    }
    d[x] = 0;
    int nod, next;
    c.push(Nod(1, 0));
    while (!c.empty())
    {
        nod = c.top().y;
        c.pop();
 
        for (vector <Nod>::iterator it = v[nod].begin(); it != v[nod].end(); ++it) {
            next = it->y;
            if (d[next] > d[nod] + it->cost) {
                d[next] = d[nod] + it->cost;
                c.push(Nod(next, d[next]));
            }
        }
    }
}
int main()
{
    citire();
    dijkstra_heap(1);
    for (int i = 2; i <= n; ++i ) {
        if (d[i]==inf) {
            g << 0 << " ";
        } else { 
            g<<d[i]<<" ";
        }
    }
}