Cod sursa(job #2365499)

Utilizator stefanst77Luca Stefan Ioan stefanst77 Data 4 martie 2019 14:09:39
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#define nmax 50007
#define oo 1e9

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

int n, m;
vector < pair <int, int> > L[nmax];
priority_queue < pair <int, int> > q;
int viz[nmax], drum[nmax];

void Citire()
{
    int i, x, y, c;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        L[x].push_back({y, c});
    }
}

void Dijkstra()
{
    int i, el, nod, cost;
    for (i = 1; i <= n; i++)
        drum[i] = oo;
    drum[1]  = 0;
    q.push({1, 0});
    while (!q.empty())
    {
        el = q.top().first;
        q.pop();
        if (viz[el] == 0)
        {
            viz[el] = 1;
            for (auto w : L[el])
            {
                nod = w.first;
                cost = w.second;
                if (drum[nod] > drum[el] + cost)
                {
                    drum[nod] = drum[el] + cost;
                    q.push({nod, cost});
                }
            }
        }
    }
}

int main()
{
    Citire();
    Dijkstra();
    for (int i = 2; i <= n; i++)
        fout << drum[i] << " ";
    fout << "\n";
    fin.close();
    fout.close();
    return 0;
}