Cod sursa(job #2977465)

Utilizator CalinHanguCalinHangu CalinHangu Data 11 februarie 2023 17:36:39
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>

#define ll long long
#define pb push_back
#define bg begin()
#define ed end()
#define cl clear()
#define pii pair<int, int>
#define x first
#define y second

///#define int ll

using namespace std;

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

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

vector<pii> v[NMAX];
priority_queue<pii> pq;

int n, m, dist[NMAX];

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

void solve(){
    dijkstra(1);
    for(int i = 2; i <= n; ++i){
        if(dist[i] == INF)
            out << 0 << ' ';
        else
            out << dist[i] << ' ';
    }
    out << nl;
}

int main(){
    in >> n >> m;
    for(int i = 1; i <= m; ++i){
        int a, b, c;
        in >> a >> b >> c;
        v[a].pb({b, c});
    }
    solve();
    return 0;
}