Cod sursa(job #3040271)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 29 martie 2023 17:29:54
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 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 = 2e9 + 1;

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

int d[max_size], n;
vector <pair <int, int>> mc[max_size];
priority_queue <str> pq;

void djk ()
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;
    pq.push({1, 0});
    while (!pq.empty())
    {
        int nod = pq.top().nod, cost = pq.top().cost;
        pq.pop();
        if (cost > d[nod])
        {
            continue;
        }
        for (auto f : mc[nod])
        {
            if (d[nod] + f.second < d[f.first])
            {
                d[f.first] = d[nod] + f.second;
                pq.push({f.first, d[f.first]});
            }
        }
    }
}

int main ()
{
    int m;
    in >> n >> m;
    while (m--)
    {
        int x, y, c;
        in >> x >> y >> c;
        mc[x].push_back({y, c});
    }
    djk();
    for (int i = 2; i <= n; i++)
    {
        out << d[i] << " ";
    }
    in.close();
    out.close();
    return 0;
}