# Cod sursa(job #2141700)

Utilizator Data 24 februarie 2018 15:44:07 Algoritmul lui Dijkstra 90 cpp done Arhiva educationala 1.93 kb
``````#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<queue>
#define INF (1<<30)
#define NMAX 50010
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 dist[NMAX];
bool used[NMAX];
vector<pair<int, int> > G[NMAX];

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

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

heap.push(start);
while (!heap.empty()) {
int node = heap.top();
heap.pop();

if (!used[node]) {
used[node] = true;
for (auto &it : G[node]) {
if (dist[it.first] > dist[node] + it.second) {
dist[it.first] = dist[node] + it.second;
heap.push(it.first);
used[node] = false;
}
}
}
}
}

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

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

for (i = 1; i <= N; i++) {
dist[i] = INF;
}

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

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

return 0;
}
``````