Cod sursa(job #2990154)

Utilizator manudragoDragomir Manuel manudrago Data 7 martie 2023 16:23:44
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 50005;
const int INF = 0x3f3f3f3f;

vector < pair < int, int > > G[NMAX];
priority_queue < pair < int, int > > pq;
int dist[NMAX];
bool viz[NMAX];

int N, M;

void read(){
    fin >> N >> M;
    for(int i = 0; i < M; ++i){
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
}

void dijkstra(){
    dist[1] = 0;

    pq.push({0, 1});
    while(!pq.empty()){
        auto cap = pq.top();
        pq.pop();

        int cost = -cap.first;
        int nod = cap.second;

        for(auto nbr: G[nod]){
            int new_cost = cost + nbr.second;
            if(new_cost < dist[nbr.first]){
                dist[nbr.first] = new_cost;
                pq.push({-new_cost, nbr.first});
            }
        }
    }
}

void print(){
    for(int i = 2; i <= N; i++){
        if(dist[i] == INF){
            fout << 0 << " ";
        }
        else{
            fout << dist[i] << " ";
        }

    }
}

int main()
{
    read();
    for(int i = 1; i <= N; i++){
        dist[i] = INF;
    }
    dijkstra();
    print();
    return 0;
}