# Cod sursa(job #2141601)

Utilizator Data 24 februarie 2018 14:47:58 Algoritmul lui Dijkstra 0 cpp done Arhiva educationala 1.64 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;
// }

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

heap.push(make_pair(0, start));
while (N) {
pair<int, int> node = heap.top();
int d = node.first;
heap.pop();
dist[node.second] = d;
N--;
for (auto &it : G[node.second]) {
heap.push(make_pair(d + it.second, it.first));
}
}
}

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

int N, M, x, y, c, i;
vector<int> dist(N + 1, 0);
Graph G;

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

int start = 1;
dijkstra(G, start, N, dist);
for (i = 2; i <= N; i++) {
cout << dist[i] << ' ';
}

return 0;
}
``````