Cod sursa(job #3283745)

Utilizator Y.MalmsteenB.P.M. Y.Malmsteen Data 10 martie 2025 13:18:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <queue>

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

struct muchie
{
    int y, w;

    bool operator<(const muchie &m) const
    {
        return w > m.w;
    }
};

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, w;
    f >> N >> M;
    for(int i = 1; i <= M; ++i)
    {
        f >> x >> y >> w;
        G[x].push_back({y, w});
    }
}

void Dijkstra(int nod)
{
    D[nod] = 0;
    Q.push({nod, 0});
    while(!Q.empty())
    {
        muchie crt = Q.top();
        Q.pop();
        if(crt.w > D[crt.y])
            continue;
        for(muchie& m : G[crt.y])
        {
            int cost = D[crt.y] + m.w;
            if(D[m.y] > cost)
            {
                D[m.y] = cost;
                Q.push({m.y, D[m.y]});
            }
        }
    }
}

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