Cod sursa(job #3038942)

Utilizator begusMihnea begus Data 27 martie 2023 22:18:44
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX=5e4+1;

vector<pair<int, int>> adj[NMAX];
int n, m, dist[NMAX];
bool processed[NMAX];

int main(){
    fin >> n >> m;
    while(m--){
        int x, y, w;
        fin >> x >> y >> w;
        adj[x].push_back({y, w});
    }
    for(int i=1; i<=n; i++) dist[i]=INT_MAX/2;
    priority_queue<pair<int, int>> q;
    q.push({0, 1});
    dist[1]=0;
    while(!q.empty()){
        int a=q.top().second; q.pop();
        if(processed[a]) continue;
        processed[a]=true;
        for(auto u : adj[a]){
            int b=u.first, w=u.second;
            if(dist[b]>dist[a]+w){
                dist[b]=dist[a]+w;
                q.push({-dist[b], b});
            }
        }
    }
    for(int i=2; i<=n; i++){
        if(dist[i]==INT_MAX/2) fout << 0 << ' ';
        else fout << dist[i] << ' ';
    }
}