Cod sursa(job #3207409)

Utilizator csamoilasamoila ciprian casian csamoila Data 26 februarie 2024 09:38:52
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>
#define NMAX 50001
#define INF 5e9 + 5

using namespace std;

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

int N, M;
vector<pair<int, int>> ADJ[NMAX];
long long Dist[NMAX];

void Dijkstra() {
    priority_queue<pair<long long, int>> q;
    q.push({0, 1});
    for(int i = 1; i <= N; i++) Dist[i] = INF;
    Dist[1] = 0;
    while (!q.empty()) {
        int cur = q.top().second;
        long long d = -q.top().first;
        q.pop();

        for (auto next : ADJ[cur]) {
            long long new_dist = d + next.second;
            if(Dist[next.first] > new_dist) {
                Dist[next.first] = new_dist;
                q.push({-new_dist, next.first});
            }
        }
    }
}

int main()
{
    fin >> N >> M;
    for(int i = 1; i <= M; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        ADJ[a].push_back({b, c});
    }
    Dijkstra();
    for(int i = 2; i <= N; i++)
        fout << Dist[i] << ' ';
    return 0;
}