Cod sursa(job #3284328)

Utilizator raulthestormIlie Raul Ionut raulthestorm Data 11 martie 2025 14:33:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <queue>

using namespace std;
const int NMAX = 50001,
          INF = 1e9;

struct muchie
{
    int y, c;
    bool operator<(const muchie B) const
    {
        return c > B.c;
    }
};

int n, m, d[NMAX];
vector<muchie> G[NMAX];
priority_queue<muchie> Q;

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

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

void dijkstra(int nod)
{
    d[nod] = 0;
    Q.push({nod, 0});
    while(!Q.empty())
    {
        muchie crt = Q.top();
        Q.pop();
        if(crt.c > d[crt.y])
            continue;
        //
        for(const auto &m : G[crt.y])
        {
            int cost = d[crt.y] + m.c;
            if(cost < d[m.y])
            {
                d[m.y] = cost;
                Q.push({m.y, d[m.y]});
            }
        }
    }
}

int main()
{
    citire();
    for(int i = 1; i <= n; i++)
        d[i] = INF;
    //
    dijkstra(1);
    //
    for(int i = 2; i <= n; i++)
        if(d[i] == INF)
            g << "0 ";
        else
            g << d[i] << ' ';
    //
    f.close();
    g.close();
    return 0;
}