Cod sursa(job #2968152)

Utilizator Teodor11Posea Teodor Teodor11 Data 20 ianuarie 2023 19:04:48
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

#define Inf 1000000000

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

using PI = pair<int, int>; /// pereche
int n, m, x, y, D[50001], w;
vector<PI> G[50001];

void dis()
{
    for (int i = 1; i <= n; ++i) {
        cout << "(Nod " << i << ", Cost " << D[i] << ") ";
    }
    cout << endl;
}

void dijkstra(int nod)
{
    priority_queue < PI , vector<PI> , greater<PI> > Q;
    D[nod] = 0;
    Q.push({0 , nod});
    while(!Q.empty())
    {
       x = Q.top().first; /// COSTUL MINIM DE LA NODUL SURSA PANA LA NODUL y (NODUL CURENT)
       y = Q.top().second; /// NODUL CURENT
       Q.pop();
       //if(x > D[y]) continue;
       int k = G[y].size();
       for(int i = 0; i < k; ++i)
       {
           int nodnou = G[y][i].first; /// NOD VECIN
           int costnou = G[y][i].second; /// COST MUCHIE
           if(D[nodnou] > D[y] + costnou) /// D[nodnou] = costul nodului vecin , D[y] = costul nodului curent , costnou = costul muchiei ce leaga cele doua noduri
           {
               D[nodnou] = D[y] + costnou; /// ACTUALIZAM COSTUL NODULUI VECIN
               Q.push({D[nodnou] , nodnou}); /// INTRODUCEM IN COADA COSTUL PANA LA NODUL VECIN SI PE ACESTA
           }
       }
    }
}
int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y >> w;
        G[x].push_back({y , w});
    }
    for(int i = 1 ; i <= n ; i++)
        D[i] = Inf;
    dijkstra(1);
    for(int i = 2; i <= n ; i++)
        if (D[i] == Inf) {
            fout << 0 << ' ';
        }
        else {
            fout << D[i] << " ";
        }
}