Cod sursa(job #1766557)

Utilizator BlackNestaAndrei Manaila BlackNesta Data 28 septembrie 2016 08:25:36
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define inf (1<<30)

using namespace std;

struct muchie
{
    int nod, cost;
    bool operator < (const muchie &A)const
    {
        return cost > A.cost;
    }
};

priority_queue <muchie> q;
vector <muchie> L[Nmax];
muchie w1, w;
int n, m, dij[Nmax];

void Citire()
{
    ifstream f("dijkstra.in");
    f >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        int x;
        f >> x >> w.nod >> w.cost;
        L[x].push_back(w);
    }
    f.close();
}

void Dijkstra()
{
    w.nod = 1;
    w.cost = 0;
    q.push(w);
    for(int i = 1; i <= n; i++)
        dij[i] = inf;
    dij[1] = 0;
    q.push(w);
    while(!q.empty())
    {
        w = q.top();
        q.pop();
        for(unsigned i = 0; i < L[w.nod].size(); i++)
        {
            int j = L[w.nod][i].nod;
            int cc = L[w.nod][i].cost;
            if(dij[j] > dij[w.nod] + cc)
            {
                dij[j] = dij[w.nod] + cc;
                w1.nod = j;
                w1.cost = dij[j];
                q.push(w1);
            }
        }
    }
}

void Afisare()
{
    ofstream g("dijkstra.out");
    for(int i = 2; i <= n; i++)
        if(dij[i] == inf) g << "0 ";
        else g << dij[i] << " ";
    g << "\n";
    g.close();
}

int main()
{
    Citire();
    Dijkstra();
    Afisare();
    return 0;
}