Cod sursa(job #3005668)

Utilizator CalinHanguCalinHangu CalinHangu Data 17 martie 2023 10:03:30
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 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], inq[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, inq[source] = 1;
    pq.push({source, 0});
    while(!pq.empty()){
        int cur_node = pq.top().x;
        pq.pop();
        inq[cur_node] = 0;
        for(auto neigh: v[cur_node]){
            if(dist[neigh.x] > dist[cur_node] + neigh.y){
                dist[neigh.x] = dist[cur_node] + neigh.y;
                if(inq[neigh.x] == 0){
                    pq.push({neigh.x, dist[neigh.x]});
                    inq[neigh.x] = 1;
                }
            }
        }
    }
}

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] << ' ';
    }
    out << nl;
    return 0;
}