Cod sursa(job #2670645)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 10 noiembrie 2020 13:31:14
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <memory.h>

const int NMAX = 5e4;

int n, m;

std::vector<std::pair<int, int>> graph[1 + NMAX];

int dist[1 + NMAX];

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> pq;

void read () {
  std::ifstream in("dijkstra.in");

  in >> n >> m;

  int x, y, z;
  for (int i = 1; i <= m; ++i) {
    in >> x >> y >> z;

    graph[x].emplace_back(z, y);
  }

  in.close();
}

void dijkstra(int start) {
  memset(dist, -1, sizeof(dist));

  pq.emplace(0, start);
  dist[start] = 0;

  while (!pq.empty()) {
    int node = pq.top().second;
    int val = pq.top().first;
    pq.pop();

    if (val > dist[node])
      continue;

    for (auto& edge : graph[node]) {
      if (dist[edge.second] == -1 || dist[edge.second] > val + edge.first) {
        pq.emplace(val + edge.first, edge.second);
        dist[edge.second] = val + edge.first;
      }
    }
  }
}

int main() {
  read();

  dijkstra(1);

  std::ofstream out("dijkstra.out");
  for (int i = 2; i <= n; ++i)
    out << dist[i] << ' ';

  out.close();
  return 0;
}