Cod sursa(job #2973714)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 1 februarie 2023 18:28:17
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
//
// Created by Radu Buzas on 22.11.2022.
//
#include <fstream>
#include <vector>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;

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

int n, m;
struct costNode{
    int * cost;
    int node;
    bool operator< (const costNode & o) const{
        return  (* this -> cost > * o.cost);
    }
    costNode(int * cost_ptr = 0, int node_ = 0): cost(cost_ptr), node(node_) {}
};

vector<pair<int, int>> graph[50001];
int d[50001];

void dijkstra(int x){
    d[x] = 0;
    priority_queue<costNode> q;
    for (int i = 1; i <= n; ++i)
        q.push({d + i, i});
    while (!q.empty()){
        int node = q.top().node;
        int cost = d[node];
        q.pop();
        for (pair<int, int> k : graph[node])
            if(cost + k.first < d[k.second])
                d[k.second] = cost + k.first;
    }
}

int main(){
    int x, y, c;
    in >> n >> m;
    for(int i = 1; i <=n; ++i)
        d[i] = inf;
    for(int i = 1; i <= m; ++i){
        in >> x >> y >> c;
        graph[x].push_back({c, y});
//        graph[y].push_back({x, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if((d[i] ^ inf) == 0)
            out << 0 << ' ';
        else
            out << d[i] << ' ';
    }
    in.close();
    out.close();
    return 0;
}