# Cod sursa(job #2170549)

Utilizator Data 15 martie 2018 08:07:00 Algoritmul lui Dijkstra 20 cpp done Arhiva educationala 1.27 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#define NMAX 50010
using namespace std;

typedef pair<int, int> int_pair;

vector<int_pair> G[NMAX];
int dist[NMAX];
bool used[NMAX];

struct cmp {
bool operator() (const int& i, const int &j) {
return dist[i] > dist[j];
}
};

void dijkstra(int N, int start) {
priority_queue<int, vector<int>, cmp> heap;
memset(dist, -1, sizeof(dist));
dist[start] = 0;

heap.push(start);

int node;
while (N) {
node = heap.top();
heap.pop();
if (used[node]) continue;
used[node] = true;
N--;

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

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

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

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

return 0;
}
``````