Cod sursa(job #3321965)

Utilizator Maries_MihaiMaries Mihai Maries_Mihai Data 11 noiembrie 2025 20:26:06
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

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

const int nmax = 50005;
const int oo = (1 << 30);
int n, m;
int dist[nmax];
bool vizitat[nmax];
priority_queue <pair<int, int>> PQ;
vector <pair <int, int>> G[nmax];

void dijkstra(int nstart, int n){
    for(int i = 2; i <= n; i++){
        dist[i] = oo;
    }
    dist[1] = 0;

    PQ.push({0, nstart});
    while(PQ.size()){
        int nod = PQ.top().second;
        PQ.pop();

        if(!vizitat[nod]){
            vizitat[nod] = true;

        for(auto it : G[nod]){
            if(dist[it.first] > dist[nod] + it.second){
                dist[it.first] = dist[nod] + it.second;
                PQ.push({-dist[it.first], it.first});
                }
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    while(m--){
        int a, b, c;
        fin >> a >> b >> c;
        G[a].push_back({b, c});
    }

    dijkstra(1, n);

    for(int i = 2; i <= n; i++){
        if(dist[i] == oo)
            dist[i] = 0;
    }

    for(int i = 2; i <= n; i++)
        fout << dist[i] << " ";
    return 0;
}