Cod sursa(job #2203977)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 13 mai 2018 21:49:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <queue>
#include <vector>
#define pb push_back
#define NMAX 50005
#define INF 1e9

using namespace std;

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

struct Node{
    int y, cost;
    Node(int y, int cost): y{y}, cost{cost} {}
    bool operator<(const Node& ot) const{
        return this->cost > ot.cost;
    }
};

int n, m;
int dist[NMAX];
vector<Node>G[NMAX];
priority_queue<Node>q;


void read_data(int &n, int &m){
    f >> n >> m;
    for(int i = 1; i<=m; i++){
        int x, y, cost;
        f >> x >> y >> cost;
        G[x].pb({y, cost});
    }
}

void dijkstra(int src, int n, vector<Node>G[]){
    for(int i = 1; i<=n; i++){
        dist[i] = INF;
    }

    dist[src] = 0;
    vector<Node>::iterator it;
    q.push({src, dist[src]});
    while(!q.empty()){
        auto node = q.top();
        q.pop();
        int neigh = node.y;
        if(dist[neigh] != node.cost){
            continue;
        }
        for(it = G[neigh].begin(); it != G[neigh].end(); it++){
            if(dist[it->y] > dist[neigh] + it->cost){
                dist[it->y] = dist[neigh] + it->cost;
                q.push({it->y, dist[it->y]});
            }
        }

    }
}

void print_sol(int n, int dist[]){
    for(int i = 2; i<=n; i++){
        dist[i] != INF ? g << dist[i] << ' ' : g << 0 << ' ';
    }
}

int main(){
    read_data(n, m);
    dijkstra(1, n, G);
    print_sol(n, dist);
    return 0;
}