Cod sursa(job #2117777)

Utilizator UWantMyNameGheorghe Vlad Camil UWantMyName Data 29 ianuarie 2018 17:59:48
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define in "dijkstra.in"
#define out "dijkstra.out"
#define oo 1e7
#define Nmax 50005
using namespace std;
ifstream fin(in);
ofstream fout(out);

int n,m;
bitset <Nmax> viz;
int d[Nmax];
vector <pair <int,int> > L[Nmax];
priority_queue <pair <int,int> > q;

void Read()
{
    int i,x,y,cost;

    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        L[x].push_back({y,cost});
    }
    fin.close();
}

void Init()
{
    int i;

    for (i = 1; i <= n; i++)
        d[i] = oo;
    q.push({0,1}); /// cost, nod
    d[1] = 0;
}

void Dijkstra()
{
    int nod,cost,k;

    while (!q.empty())
    {
        k = q.top().second; /// preiau nodul
        q.pop();

        if (viz[k] == 0)
        {
            viz[k] = 1;
            for (auto i : L[k])
            {
                nod = i.first;
                cost = i.second;

                if (d[nod] > d[k] + cost)
                {
                    d[nod] = d[k] + cost;
                    q.push({-d[nod],nod});
                }
            }
        }
    }
}

void Afis()
{
    int i;

    for (i = 2; i <= n; i++)
        if (d[i] != oo) fout << d[i] << " ";
        else fout << "0 ";
    fout.close();
}

int main()
{
    Read();
    Init();
    Dijkstra();
    Afis();

    return 0;
}