Cod sursa(job #2066139)

Utilizator stefan_creastaStefan Creasta stefan_creasta Data 14 noiembrie 2017 18:35:43
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 50005;
const int INF =  0x7fffffff;
struct MUCHIE {
  int nod;
  int cost;
  bool operator < (const MUCHIE &other) const {
    return this->cost < other.cost;
  }
};
struct NOD {
  int nod;
  int cost;
};
vector <NOD> v[NMAX];
int cost[NMAX];
void dijkstra(int s, int n) {
  for (int u = 1; u <= n; ++u) {
    cost[u] = INF;
  }
  cost[s] = 0;
  priority_queue <MUCHIE> q;
  q.push({s, 0});
  while (!q.empty()) {
    int u = q.top().nod;
    if (cost[u] == q.top().cost) {
      q.pop();
      for (NOD e : v[u]) {
        if (cost[e.nod] > cost[u] + e.cost) {
          cost[e.nod] = cost[u] + e.cost;
          q.push({e.nod, cost[e.nod]});
        }
      }
    } else {
      q.pop();
    }
  }
}


int main() {
  int n, m;
  freopen("dijkstra.in", "r", stdin);
  freopen("dijkstra.out", "w", stdout);
  scanf("%d%d", &n, &m);
  for(int i = 1; i <= m; ++i) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    v[a].push_back({b, c});
  }
  dijkstra(1, n);
  for(int i = 2; i <= n; ++i) {
    if(cost[i] == INF) {
      cost[i] = 0;
    }
    printf("%d ", cost[i]);
  }
  printf("\n");
  return 0;
}