# Cod sursa(job #2141594)

Utilizator Data 24 februarie 2018 14:38:17 Algoritmul lui Dijkstra 0 cpp done Arhiva educationala 1.25 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<map>
#include<queue>
#include<utility>
using namespace std;

typedef unordered_map< int, vector<pair<int, int> > > Graph;

map<int, int> dijkstra(Graph &G, int start) {
int N = G.size();
map<int, int> dist;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int > > > heap;

heap.push(make_pair(0, start));
while (dist.size() < N) {
pair<int, int> node = heap.top();
int d = node.first;
heap.pop();
dist[node.second] = d;

for (auto &it : G[node.second]) {
heap.push(make_pair(d + it.second, it.first));
}
}

return dist;
}

int main() {
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);

int N, M, x, y, c, i;
Graph G;

cin >> N >> M;
for (i = 0; i < N; i++) {
G[i + 1] = vector<pair<int, int> >();
}
for (i = 0; i < M; i++) {
cin >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}

int start = 1;
map<int, int> dist = dijkstra(G, start);
for (auto &it : dist) {
if (it.first != start) {
cout << it.second << ' ';
}
}

return 0;
}
``````