Cod sursa(job #2977476)

Utilizator CalinHanguCalinHangu CalinHangu Data 11 februarie 2023 17:45:44
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 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<ll, ll>
#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, source});
    while(!pq.empty()){
        pii top = pq.top();
        int cur = top.y;
        if(-pq.top().x > dist[cur]){
            pq.pop();
            continue;
        }
        pq.pop();
        for(auto neigh: v[cur]){
            if(dist[neigh.x] > dist[cur] + neigh.y){
                dist[neigh.x] = dist[cur] + neigh.y;
                pq.push({-dist[neigh.x], neigh.x});
            }
        }
    }
}

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

signed   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;
}