Cod sursa(job #3216858)

Utilizator alexandrubilaBila Alexandru-Mihai alexandrubila Data 20 martie 2024 09:11:08
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX = 100001; ///MMAX = 250001
const int INF = 0;

struct muchie
{
    int y, w; ///w - cost muchie

    bool operator <(const muchie &m) const ///am supraincarcat  '<' -> operatorul de supraincarcare;
    {
        return m.w < w;
    }

};

int N, M;
int D[NMAX]; ///D DE i = dist min de la p la i

vector <muchie> G[NMAX]; /// g de i = lista muchiilor incidente cu i -> avem nu doar muchiile, ci si costurile asociate
priority_queue<muchie> Q;

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

void citire()
{
    int x, y, w; ///w = cost asociat muchiei x, y;
    f >> N >> M;
    for (int i = 1 ; i <= M ; ++i)
    {
        f >> x >> y >> w;
        G[x].push_back({y, w});
        G[y].push_back({x, w});
    }
}

void Dijkstra(int nod)
{
    D[nod] = 0;
    Q.push({nod, 0});
    while (!Q.empty())
    {
        muchie crt = Q.top(); ///Se extrage un nod din coada cu cel mai mic cost (cea mai mica distanta asociata)
        Q.pop();
        if (crt.w > D[crt.y]) ///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] = -1;
    }
    Dijkstra(1);
    //
    for (i = 2 ; i <= N; ++i)
            g << D[i] << ' ';

    return 0;
}