Cod sursa(job #1821462)

Utilizator OFY4Ahmed Hamza Aydin OFY4 Data 3 decembrie 2016 10:35:39
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <queue>

using namespace std;

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

struct edge
{
    int nod, z;
    bool operator <(const edge &aux) const
    {
        return z > aux.z;
    }
};

const int inf = 1000000000, Max = 50010;
vector<edge> v[Max];
priority_queue<edge> h;
int d[Max], n;

void dijkstra(int nod)
{
    for(int i = 1; i <= n; ++i)
        d[i] = inf;

    d[nod] = 0;

    h.push({nod, 0});
    while(!h.empty())
    {
        int nod = h.top().nod, z = h.top().z;
        h.pop();

        if(z > d[nod])
            continue;

        for(vector<edge> :: iterator it = v[nod].begin(); it != v[nod].end(); ++it)
        {
            if(d[nod] + it -> z < d[it  -> nod])
            {
                d[it -> nod] = d[nod] + it -> z;
                h.push({it -> nod, d[it -> nod]});
            }
        }
    }
}

int main()
{
    int m, x, y, z;
    in >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        in >> x >> y >> z;
        v[x].push_back({y, z});
    }

    dijkstra(1);
    for(int i = 2; i <= n; ++i)
    {
        if(d[i] == inf)
            out << "0 ";
        else
            out << d[i] << " ";
    }

    return 0;
}