Cod sursa(job #2488788)

Utilizator bogdanvladmihaiBogdan Vlad-Mihai bogdanvladmihai Data 7 noiembrie 2019 17:14:08
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

const int MAX_N = 50005;
const int INF = (1 << 25);

int n, m;

std::vector <std::pair<int, int>> g[MAX_N];
std::vector <int> distances(MAX_N, INF);
std::vector <bool> in_queue(MAX_N);

struct get_max {
  bool operator () (int u, int v) {
    return distances[u] > distances[v];
  }
};

std::priority_queue <int, std::vector<int>, get_max> q;

int main() {
  int u, v, val;
  // freopen("dijkstra.in", "r", stdin);
  // freopen("dijkstra.out", "w", stdout);
  scanf("%d %d", &n, &m);
  while (m --) {
    scanf("%d %d %d", &u, &v, &val);
    g[u].push_back(std::make_pair(v, val));
    g[v].push_back(std::make_pair(u, val));
  }
  distances[1] = 0;
  in_queue[1] = 1;
  q.push(1);
  while (q.size() > 0) {
    u = q.top();
    in_queue[u] = false;
    for (std::pair <int, int> v : g[u]) {
      if (distances[v.first] > distances[u] + v.second) {
        distances[v.first] = distances[u] + v.second;
        if (in_queue[v.first] == 0) {
          in_queue[v.first] = 1;
          q.push(v.first);
        }
      }
    }
    q.pop();
  }
  for (int i = 2; i <= n; ++i) {
    if (distances[i] == INF) {
      distances[i] = 0;
    }
    printf("%d ", distances[i]);
  }
#ifdef LOCAL_DEFINE
  std::cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
  return 0;
}