Cod sursa(job #2944725)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 22 noiembrie 2022 21:39:22
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
//
// Created by Radu Buzas on 22.11.2022.
//
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

int n, m;
vector<vector<pair<int, int>>> graph;
vector<int> d, from;
vector<bool> inQueue;

void dijkstra(int x){
    d[x] = 0;
    priority_queue<pair<int, int>> q;
    q.push({0, x});
    while (!q.empty()){
        int cost = -q.top().first;
        int nod = q.top().second;
        inQueue[nod] = false;
        q.pop();
        for (auto k : graph[nod]) {
            if(cost - k.first < d[k.second]){
                d[k.second] = cost - k.first;
                if (!inQueue[k.second]) {
                    inQueue[k.second] = true;
                    q.push({-cost + k.first, k.second});
                }
            }
        }
    }
}

int main(){
    in >> n >> m;
    graph.resize(n+1);
    inQueue.resize(n+1, false);
    d.resize(n+1, ((unsigned)1 << 31) -1);
    for(int i = 1; i <= m; ++i){
        int x, y, c;
        in >> x >> y >> c;
        graph[x].emplace_back(-c, y);
//        graph[y].push_back({x, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if(d[i] == ((unsigned)1 << 31) -1)
            out << 0 << ' ';
        out << d[i] << ' ';
    }
    in.close();
    out.close();
    return 0;
}