Pagini recente » Cod sursa (job #2514453) | Cod sursa (job #1043851) | Cod sursa (job #2297822) | Cod sursa (job #926062) | Cod sursa (job #2505661)
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#define pb push_back
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijktra.out");
const int MAXN = 50010;
const int INF = 0x3f3f3f3f;
struct Node {
int node, cost;
bool operator<(const Node &other) const {
if (cost != other.cost)
return cost < other.cost;
return node < other.node;
}
};
int n, m, dist[MAXN];
vector<Node> edges[MAXN];
set<Node> heap;
void read() {
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int x, y, c;
fin >> x >> y >> c;
edges[x].pb({y, c});
}
}
void initialize() {
for (int i = 1; i <= n; ++i)
dist[i] = INF;
}
void dijkstra() {
dist[1] = 0;
heap.insert({1, 0});
while (!heap.empty()) {
int node = heap.begin()->node;
heap.erase(heap.begin());
for (const auto &it: edges[node])
if (dist[it.node] > dist[node] + it.cost) {
if (dist[it.node] != INF)
heap.erase({it.node, dist[it.node]});
dist[it.node] = dist[node] + it.cost;
heap.insert({it.node, dist[it.node]});
}
}
}
void print() {
for (int i = 2; i <= n; ++i)
fout << dist[i] << ' ';
}
int main() {
read();
initialize();
dijkstra();
print();
return 0;
}