Cod sursa(job #2621851)

Utilizator WholeGrainAndy N WholeGrain Data 30 mai 2020 21:03:35
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <set>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

int const NMAX = 5e4;
const int INF = 1e9;

struct Edge {
  int node;
  int cost;

  bool operator<(Edge other) const {
    if (cost != other.cost) {
      return cost < other.cost;
    } else {
      return node < other.node;
    }
  }
};

int n, m;
vector<Edge> g[1 + NMAX];
int dist[1 + NMAX];
int visited[1 + NMAX];
set<Edge> pretenders;

int main() {
  in >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v, w;
    in >> u >> v >> w;
    u--; v--;
    g[u].push_back({v, w});
  }
  for (int i = 1; i < n; i++) {
	dist[i] = INF;
  }
  dist[0] = 0;
  pretenders.insert({0, 0});
  while(!pretenders.empty()) {
    //red phase
    Edge e = *pretenders.begin();
    pretenders.erase(e);
    int from = e.node;
    if(visited[from] == 0) {
      visited[from] = 1;
      //dist[from] = e.cost;

      //blue phase
      for (Edge p : g[from]) {
         int to = p.node;
         int delta = p.cost;
         if(dist[from] + delta < dist[to]) {
	  	dist[to] = dist[from] + delta;
           pretenders.insert({to, dist[to]});
         }
       }
     }
  }
  for (int i = 1; i < n; i++) {
    if (dist[i] == INF) {
        out << 0 << " ";
    }
    else {
        out << dist[i] << " ";
    }
  }
  out << "\n";
  return 0;
}