Cod sursa(job #2462898)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 27 septembrie 2019 23:27:24
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include<bits/stdc++.h>
#define pb push_back
#define INF 1e9
#define NMAX 50005
#define MMAX 250005
using namespace std;

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

class Node{
public:
    int y, cost;

    Node(const int& y, const int& cost): y{y}, cost{cost} {}

    bool operator<(const Node& other) const {
        return this->cost > other.cost;
    }
};

vector<Node> Graph[NMAX];
int n, m, dist[NMAX];
priority_queue<Node> pq;

void read_data(){
    in >> n >> m;
    for(int i = 0; i<m; i++){
        int x, y, c;
        in >> x >> y >> c;
        Graph[x].pb({y, c});

    }
}

void dijkstra(){
    for(int i = 0; i<= n; i++){
        dist[i] = INF;
    }
    dist[1] = 0;
    pq.push({1, dist[1]});
    while(!pq.empty()){
        auto top = pq.top();
        auto cost = top.cost;
        if(cost != dist[top.y]){
            continue;
        }
        pq.pop();
        for(const auto& neigh : Graph[top.y]){
            if(dist[neigh.y] > dist[top.y] + neigh.cost){
                dist[neigh.y] = dist[top.y] + neigh.cost;
                pq.push({neigh.y, dist[neigh.y]});
            }
        }
    }
}

int main(){
    read_data();
    dijkstra();
    for(int i = 2; i<=n; i++){
        dist[i] == INF ? out << '0' << ' ' : out << dist[i] << ' ';
    }
    return 0;
}