Pagini recente » Cod sursa (job #1334544) | Cod sursa (job #589438) | Cod sursa (job #2213386) | Cod sursa (job #776895) | Cod sursa (job #3251114)
#include <algorithm>
#include <fstream>
#include <cstring>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
const int NMAX = 50005;
const int INF = 0x3f3f3f3f;
vector<pair<int, int>> G[NMAX];
int dist[NMAX];
int main() {
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
///citim n,m
int n, m;
f >> n >> m;
for (int i = 0; i < m; ++i) {
int from, to, cost;
f >> from >> to >> cost;
G[from].push_back(make_pair(to, cost));
/// se mai adauga in o comanda ca mai sus cu from si to inversate pt graf neorientat
}
/// initializare vector cu valori foarte mari, chiar imposibile
memset(dist, INF, sizeof dist);
dist[1] = 0;
set<pair<int, int>> h;
h.insert(make_pair(0, 1));
while (!h.empty()) {
int node = h.begin()->second;
int d = h.begin()->first;
h.erase(h.begin());
///ATENTIE, eliberam cum luam un element
for (auto &it: G[node]) {
int to = it.first;
int cost = it.second;
///daca se gaseste o distanta mai buna
if (dist[to] > dist[node] + cost) {
if (dist[to] != INF) {///daca este prima data cand ajungem
///punem doar valoarea de acum
h.erase(h.find(make_pair(dist[to], to)));
}
dist[to] = dist[node] + cost;///adaugam valoarea de acum
h.insert(make_pair(dist[to], to));///se pune noul noi in dijkstra
}
}
}
for (int i = 2; i <= n; ++i) {
if (dist[i] == INF) {
dist[i] = 0;
}
g << dist[i] << ' ';
}
g << '\n';
f.close();
g.close();
}