Cod sursa(job #2364422)

Utilizator loo_k01Luca Silviu Catalin loo_k01 Data 4 martie 2019 08:26:44
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
#define oo 2000000000
using namespace std;

const int nMax = 50005;

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

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

vector < Db > L[nMax];
priority_queue < Db > q;
int n, m;
int d[nMax];
bool v[nMax];

void Read()
{
    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, x, nod;
    for (i = 1; i <= n; i++)
        d[i] = oo;
    q.push({1, 0});
    d[1] = 0;
    v[1] = true;
    while (!q.empty())
    {
        nod = q.top().nod;
        q.pop();
        v[nod] = false;
        for (auto w : L[nod])
        {
            x = w.nod;
            if (d[x] > d[nod] + w.cost)
            {
                d[x] = d[nod] + w.cost;
                if (!v[x])
                {
                    q.push({x, d[x]});
                    v[x] = true;
                }
            }
        }
    }
}

int main()
{
    Read();
    Dijkstra();
    int i;
    for (i = 2; i <= n; i++)
        fout << d[i] << " ";
    fin.close();
    fout.close();

    return 0;
}