Cod sursa(job #2611370)

Utilizator cristi1616Olaru Cristian cristi1616 Data 6 mai 2020 19:17:00
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>

#define NMAX 50010
#define oo (1 << 30)

using namespace std;

class Task {
public:
  void solve() {
    read_input();
    get_result();
    print_output();
  }

private:
  int n, m;
  int source;
  vector<pair<int, int>> adj[NMAX];
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 std::greater<pair<int, int>>>
      pq;
  vector<int> d;
  vector<int> p;
  void read_input() {
    ifstream fin("dijkstra.in");
    fin >> n >> m;
    d.resize(n + 1);
    source = 1;
    for (int i = 1; i <= m; ++i) {
      int x, y, c;
      fin >> x >> y >> c;
      adj[x].push_back({y, c});
    }
  }

  void get_result() { Dijkstra(source, d); }

  void Dijkstra(int source, vector<int> &d) {
    for (int i = 1; i <= n; ++i) {
      d[i] = oo;
    }
    d[source] = 0;
    pq.push({d[source], source});
    while (!pq.empty()) {
      auto entry = pq.top();
      pq.pop();
      int cost = entry.first;
      int node = entry.second;
      if (cost > d[node]) {
        continue;
      }
      for (auto &edge : adj[node]) {
        int neighbour = edge.first;
        int cost_edge = edge.second;
        if (d[node] + cost_edge < d[neighbour]) {
          d[neighbour] = d[node] + cost_edge;
          pq.push({d[neighbour], neighbour});
        }
      }
    }
    for (int i = 1; i <= n; ++i) {
      if (d[i] == oo) {
        d[i] = 0;
      }
    }
  }
  void print_output() {
    ofstream fout("dijkstra.out");
    for (int i = 1; i <= n; ++i) {
      if (i == source) {
        continue;
      }
      fout << d[i] << " ";
    }
    fout << "\n";
  }
};

int main() {
  Task *task = new Task();
  task->solve();
  delete task;
  return 0;
}