Cod sursa(job #2973722)

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

ifstream in("grader_test8.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;
    set<costNode> q;
    q.insert({d + x, x});
    while (!q.empty()){
        int node = q.begin() -> node;
        int cost = d[node];
        q.erase(q.begin());
        for (pair<int, int> k: graph[node])
            if (cost + k.first < d[k.second]) {
                d[k.second] = cost + k.first;
                q.insert({d + k.second, k.second});
            }
    }
}

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;
}