Cod sursa(job #3239877)

Utilizator ChopinFLazar Alexandru ChopinF Data 8 august 2024 15:01:56
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
using namespace std;
std::string file = "dijkstra";
std::ifstream fin(file + ".in");
std::ofstream fout(file + ".out");
// #define fin std::cin
// #define fout std::cout
struct elem {
  int nod, cost;
  bool operator<(const elem &ot) const { return (cost >= ot.cost); }
};
int n, m;
std::vector<std::vector<elem>> gf;
std::vector<int> d;
void dj(int start) {
  d[start] = 0;
  std::priority_queue<elem> pq;
  pq.push({start, 0});
  while (!pq.empty()) {
    auto current = pq.top();
    int currentNode = current.nod;
    pq.pop();
    for (const auto &nextNode : gf[currentNode]) {
      if (d[currentNode] + nextNode.cost < d[nextNode.nod]) {
        d[nextNode.nod] = d[currentNode] + nextNode.cost;
        pq.push({nextNode.nod, d[nextNode.nod]});
      }
    }
  }
}
int32_t main(int32_t argc, char *argv[]) {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);
  fin >> n >> m;
  gf.resize(n + 1);
  d.resize(n + 1, INT_MAX);
  for (int i = 0; i < m; ++i) {
    int n1, n2, c;
    fin >> n1 >> n2 >> c;
    gf[n1].push_back({n2, c});
  }
  dj(1);
  for (int i = 2; i <= n; ++i) {
    fout << d[i] << " ";
  }
  fout << "\n";
  return 0;
}