Cod sursa(job #3353540)

Utilizator justy41Babiciu Iustin justy41 Data 8 mai 2026 09:15:50
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

#define INF 1000000000

vector<pair<int, int>> G[50001];
priority_queue<pair<int, int>> PQ;
bool viz[50001] = {0};
int dist[50001] = {0};

void dijkstra(int start, int n) {
    for(int i = 1; i<=n; i++) {
        dist[i] = INF;
    }

    for(int i = 1; i<=n; i++) {
        viz[i] = false;
    }

    PQ.push({0, start});
    dist[start] = 0;

    while(!PQ.empty()) {
        int nod = PQ.top().second;
        PQ.pop();

        if(!viz[nod]) {
            viz[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});
                }
            }
        }
    }
}

void citire() {
    int n, m, a, b, c;
    fin>>n>>m;

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

    dijkstra(1, n);

    for(int i = 2; i<=n; i++) {
        if(dist[i] == INF && i != 1) {
            dist[i] = 0; // Nu este drum de la p la nod
        }

        fout<<dist[i]<<" ";
    }
}

int main() {
    citire();

    return 0;
}