Pagini recente » Cod sursa (job #2107860) | Cod sursa (job #143770) | Cod sursa (job #1775624) | Cod sursa (job #592458) | Cod sursa (job #2145802)
#include <fstream>
#include <string>
#include <vector>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int MAXN = 50005;
const int INF = 0x3f3f3f3f;
struct arc {
int to, weight;
};
vector<arc> Graph[MAXN];
int n, m;
int dist[MAXN];
void init() {
fin >> n >> m;
for (int i = 0; i < m; i++) {
int from, to, cost;
fin >> from >> to >> cost;
Graph[from].push_back({ to,cost });
}
for (int i = 1; i <= n; i++) {
dist[i] = INF;
}
dist[1] = 0;
}
struct comp {
bool operator() (const arc& left, const arc& right) const
{
return left.weight < right.weight;
}
};
void dijkstra(int start = 1) {
set<arc,comp> heap;
heap.insert({ start,0 });
while (!heap.empty()) {
int node = heap.begin()->to;
heap.erase(heap.begin());
for (arc a : Graph[node]) {
int to = a.to;
int weight = a.weight;
if (dist[to] > dist[node] + weight) {
if (dist[to] != INF) {
heap.erase(heap.find({ to,dist[to] }));
}
dist[to] = dist[node] + weight;
heap.insert({ to,dist[to] });
}
}
}
}
void output() {
for (int i = 2; i <= n; ++i) {
if (dist[i] == INF) {
dist[i] = 0;
}
fout << dist[i] << ' ';
}
fout << '\n';
}
int main() {
init();
dijkstra();
output();
return 0;
}