# Cod sursa(job #2170374)

Utilizator Data 14 martie 2018 23:56:46 Algoritmul lui Dijkstra 20 cpp done Arhiva educationala 1.32 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

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

vector<int> dijkstra(Graph &G, int start) {
int N = G.size() - 1;
priority_queue<int_pair, vector<int_pair>, greater<int_pair> > heap;
vector<int> dist(N + 1, -1);
vector<bool> used(N + 1, false);

int_pair p;
dist[start] = 0;
heap.push(make_pair(0, start));
while (N) {
p = heap.top();
heap.pop();
if (used[p.second]) continue;
used[p.second] = true;
N--;

for (auto &edge : G[p.second]) {
if (dist[edge.first] == - 1 || dist[edge.first] > dist[p.second] + edge.second) {
dist[edge.first] = dist[p.second] + edge.second;
heap.push(make_pair(dist[edge.first], edge.first));
}
}
}

return dist;
}

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

int N, M, x, y, c, i;
cin >> N >> M;

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

vector<int> dist = dijkstra(G, 1);
for (i = 2; i <= N; i++) {
cout << ((dist[i] == -1) ? 0 : dist[i]) << ' ';
}

return 0;
}
``````