Cod sursa(job #3273757)

Utilizator AsandeiStefanAsandei Stefan-Alexandru AsandeiStefan Data 3 februarie 2025 19:08:21
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bitset>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int nmax = 1e5;
const uint64_t inf = 0x3f3f3f3f;

struct edge {
  uint64_t node, cost;
};

uint64_t n, m, a, b, c, dist[nmax + 1];
vector<edge> g[nmax + 1];

struct node_cmp {
  bool operator()(int lhs, int rhs) const { return dist[lhs] > dist[rhs]; }
};

void dijkstra(int source) {
  priority_queue<int, vector<int>, node_cmp> q;
  bitset<nmax + 1> visited = 0;

  fill(dist + 1, dist + n + 1, inf);

  dist[source] = 0;
  q.push(source);

  while (!q.empty()) {
    auto node = q.top();
    q.pop();

    visited[node] = false;

    for (auto edge : g[node]) {
      if (edge.cost + dist[node] < dist[edge.node]) {
        dist[edge.node] = edge.cost + dist[node];

        if (!visited[edge.node]) {
          q.push(edge.node);
          visited[edge.node] = true;
        }
      }
    }
  }
}

int main() {
  fin >> n >> m;
  while (m--) {
    fin >> a >> b >> c;
    g[a].push_back({b, c});
  }

  dijkstra(1);

  for (int i = 2; i <= n; i++) {
    if (dist[i] == inf)
      fout << 0 << ' ';
    else
      fout << dist[i] << ' ';
  }
  return 0;
}