Cod sursa(job #2796976)

Utilizator YusyBossFares Yusuf YusyBoss Data 9 noiembrie 2021 08:56:17
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 50000

using namespace std;

ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");

struct hatz {
  int node;
  int cost;
  bool operator < (const hatz &A) const {
    return cost > A.cost;
  }
};

int vdist[NMAX + 1];
priority_queue <hatz> pq;
vector <hatz> vnext[NMAX + 1];

void bfs() {
  int i, distcur, newnode, nodecur, newcost, n;

  pq.push({1, 0});
  vdist[1] = 0;

  while (!pq.empty()) {
    nodecur = pq.top().node;
    distcur = vdist[nodecur];
    pq.pop();

    n = vnext[nodecur].size();
    for (i = 0; i < n; i++) {
      newnode = vnext[nodecur][i].node;
      newcost = vnext[nodecur][i].cost;
      if (vdist[newnode] == -1) {
        vdist[newnode] = distcur + newcost;
        pq.push({newnode, distcur + 1});
      }
    }
  }
}

void init_vdist(int n) {
  int i;
  for (i = 1; i <= n; i++)
    vdist[i] = -1;
}

int main() {
  int n, m, i, a, b, c;
  cin >> n >> m;

  init_vdist(n);

  for (i = 0; i < m; i++) {
    cin >> a >> b >> c;
    vnext[a].push_back({b, c});
  }

  bfs();

  for (i = 2; i <= n; i++)
    cout << vdist[i] << " ";
  return 0;
}