Cod sursa(job #2893145)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 25 aprilie 2022 12:27:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int max_size = 5e4 + 1, INF = 1e9 + 1;

int d[max_size], vizitat[max_size];

struct cmp{
    bool operator()(int x, int y)
    {
        return d[x] > d[y];
    }
};

vector <pair <int, int>> edges[max_size];
priority_queue <int, vector <int>, cmp> pq;

void djk (int nod)
{
    vizitat[nod] = 1;
    d[nod] = 0;
    pq.push(nod);
    while (!pq.empty())
    {
        nod = pq.top();
        pq.pop();
        vizitat[nod] = 0;
        for (auto f : edges[nod])
        {
            if (d[nod] + f.second < d[f.first])
            {
                d[f.first] = d[nod] + f.second;
                if (vizitat[f.first] == 0)
                {
                    vizitat[f.first] = 1;
                    pq.push(f.first);
                }
            }
        }
    }
}

int main ()
{
    int n, t;
    in >> n >> t;
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    while (t--)
    {
        int x, y, c;
        in >> x >> y >> c;
        edges[x].push_back(make_pair(y, c));
    }
    djk(1);
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            out << 0 << " ";
        }
        else
        {
            out << d[i] << " ";
        }
    }
    in.close();
    out.close();
    return 0;
}