Pagini recente » Cod sursa (job #3041710) | Cod sursa (job #1681484) | Cod sursa (job #3282798) | Cod sursa (job #2088761) | Cod sursa (job #2670645)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <memory.h>
const int NMAX = 5e4;
int n, m;
std::vector<std::pair<int, int>> graph[1 + NMAX];
int dist[1 + NMAX];
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> pq;
void read () {
std::ifstream in("dijkstra.in");
in >> n >> m;
int x, y, z;
for (int i = 1; i <= m; ++i) {
in >> x >> y >> z;
graph[x].emplace_back(z, y);
}
in.close();
}
void dijkstra(int start) {
memset(dist, -1, sizeof(dist));
pq.emplace(0, start);
dist[start] = 0;
while (!pq.empty()) {
int node = pq.top().second;
int val = pq.top().first;
pq.pop();
if (val > dist[node])
continue;
for (auto& edge : graph[node]) {
if (dist[edge.second] == -1 || dist[edge.second] > val + edge.first) {
pq.emplace(val + edge.first, edge.second);
dist[edge.second] = val + edge.first;
}
}
}
}
int main() {
read();
dijkstra(1);
std::ofstream out("dijkstra.out");
for (int i = 2; i <= n; ++i)
out << dist[i] << ' ';
out.close();
return 0;
}