Cod sursa(job #3005650)

Utilizator CalinHanguCalinHangu CalinHangu Data 17 martie 2023 09:58:45
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

#define ll long long
#define pb push_back
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

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

const int NMAX = 50005;
const int INF = 1e9 + 7;
const char nl = '\n';

int n, m, dist[NMAX];

vector<pii> v[NMAX];

priority_queue<pii> pq;

void dijkstra(int source){
    for(int i = 1; i <= n; ++i)
        dist[i] = INF;
    dist[source] = 0;
    pq.push({source, 0});
    while(!pq.empty()){
        int cur_node = pq.top().x;
        int cur_weight = pq.top().y;
        pq.pop();
        for(auto neigh: v[cur_node]){
            if(dist[neigh.x] > dist[cur_node] + neigh.y){
                dist[neigh.x] = dist[cur_node] + neigh.y;
                pq.push({neigh.x, dist[neigh.x]});
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; ++i){
        int a, b, w;
        in >> a >> b >> w;
        v[a].pb({b, w});
    }
    dijkstra(1);
    for(int i = 2; i <= n; ++i){
        if(dist[i] == INF)
            out << 0 << ' ';
        else
            out << dist[i] << ' ';
    }
    return 0;
}