Cod sursa(job #3275178)

Utilizator witekIani Ispas witek Data 9 februarie 2025 13:31:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int oo = 2e9;

struct Edge {
    int node;
    int dist;

    bool operator <(const Edge& other) const {
        return dist > other.dist;
    }
};

int n, m;
vector<vector<pair<int, int>>> graph;
vector <int> d;
priority_queue <Edge> q;

void init() {
    graph = vector<vector<pair<int, int>>> (n + 1);
    d = vector <int> (n + 1, oo);
}

void dijkstra(int node) {
    d[node] = 0;
    q.push({node, 0});
    while(!q.empty()) {
        int currentNode = q.top().node;
        int currentDist = q.top().dist;
        q.pop();
        if(currentDist > d[currentNode])
            continue;
        for(const auto& neighbour : graph[currentNode]) {
            int otherNode = neighbour.first;
            int otherDist = neighbour.second;
            if(currentDist + otherDist < d[otherNode]) {
                d[otherNode] = currentDist + otherDist;
                q.push({otherNode, currentDist + otherDist});
            }
        }
    }
}

void read() {
    fin >> n >> m;
    init();
    int x, y, dist;
    for(int i = 1; i <= m; i ++) {
        fin >> x >> y >> dist;
        graph[x].push_back({y, dist});
    }
}

int main() {
    read();
    dijkstra(1);
    for(int i = 2; i <= n; ++i)
        fout << (d[i] != oo ? d[i] : 0) << " ";
}