Cod sursa(job #1824654)

Utilizator AetheryonStefan Bereghici Aetheryon Data 8 decembrie 2016 10:37:56
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
#define Nmax 100013
#define inf 0x3f3f3f3
#define node first
#define weight second
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

class Graph {
    private :
        int nodes;
        vector < pair <int,int> > g[Nmax];
        int dist[Nmax];
    public :
        Graph(int n){
            this->nodes = n;
        }

        void addEdge(int f,int t,int w){
            g[f].push_back({t,w});
        }

        void Dijkstra (int node_start) {
            priority_queue <int, vector<int> > heap;
            for (int i=1;i<=nodes;++i){
                if (i!=node_start) dist[i] = inf;
            }
            heap.push(node_start);
            while(!heap.empty()){
                int parent = heap.top();
                heap.pop();
                for (int i=0;i<g[parent].size();++i){
                    int child = g[parent][i].node;
                    if (dist[parent] + g[parent][i].weight < dist[child]){
                        heap.push(child);
                        dist[child] = dist[parent] + g[parent][i].weight;
                    }
                }
            }
            for (int i=1;i<=nodes;++i){
                if (i!=node_start) {
                    if (dist[i]!=inf) cout<<dist[i]<<" ";
                        else cout<<0<<" ";
                }
            }
        }
};

int n,m,from,to,weight,start;
int main(void){
    cin>>n>>m;
    Graph graph = Graph(n);
    while(m--){
        cin>>from>>to>>weight;
        graph.addEdge(from,to,weight);
    }
    graph.Dijkstra(1);
    return 0;
}