Cod sursa(job #2416569)

Utilizator pickleVictor Andrei pickle Data 27 aprilie 2019 18:37:51
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
// Dijkstra: Bellman-Ford
// A queue for vertices;
//  (re-)add the vertex to the queue if the distance to it has been updated.
//  re-adjust the distance to all neighbors of a vertex popped from the queue.

#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)
#define REP(i,a,b) for(int i = a; i < b; i++)

using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int Nmax = 50333;

vector<pii> G[Nmax];

int N, M, a,b,c, d[Nmax];
char inq[Nmax]; // whether the vertex is in the queue or not;

int main(void) {
  freopen("dijkstra.in", "r", stdin);
  freopen("dijkstra.out", "w", stdout);

  cin >> N >> M;
  rep(i, M) {
    cin >> a >> b >> c;
    --a;
    --b;
    G[a].push_back({ c, b});
  }
  rep(i, N) { d[i] = INF; }

  queue<int> Q;
  d[0] = 0; inq[0] = 1; Q.push(0);
  while(!Q.empty()) {
    int x = Q.front(); Q.pop();
    inq[x] = 0;
    for(pii Y: G[x]) {
      int y = Y.second;
      if (d[y] > d[x] + Y.first) {
        d[y] = d[x] + Y.first;
        if (!inq[y]) {
          inq[y] = 1;
          Q.push(y);
        }
      }
    }
  }

  for (int i = 1; i < N; ++i)
    cout << (d[i] == INF ? 0 : d[i]) << ' ';
  cout << endl;

  return 0;
}