Cod sursa(job #2857985)

Utilizator SmauSmau George Robert Smau Data 26 februarie 2022 19:05:32
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
 
#define INF 10000000
 
using namespace std;
 
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
struct Neighbour {
    int node, cost;
    friend bool operator > (const Neighbour &, const Neighbour &);
};

bool operator > (const Neighbour & a, const Neighbour & b) {
    return a.cost > b.cost;
}
 
vector <vector <Neighbour>> G;
vector <int> C;
 
int n, m;
 
void Dijkstra(int start) {
    vector <bool> used(n + 1, false);
    C = vector <int> (n + 1, INF);
 
    priority_queue <Neighbour, vector <Neighbour>, greater <Neighbour>> pq;
    pq.push({start, 0});
    C[start] = 0;
 
    while(!pq.empty()) {
        int Node = pq.top().node;
        pq.pop();

        if(used[Node]) continue;
        used[Node] = true;
 
        for(auto x : G[Node])
            if(C[x.node] > C[Node] + x.cost) {
                C[x.node] = C[Node] + x.cost;
                pq.push({x.node, C[x.node]});
            }
    }
}
 
int main() {
    fin >> n >> m;
    
    G.resize(n + 1);
 
    for(int i = 1; i <= m; i ++) {
        int x, y, c; fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
 
    Dijkstra(1);
 
    for(int i = 2; i <= n; i ++)
        fout << (C[i] != INF ? C[i] : 0) << ' ';
    
    return 0;
}