Cod sursa(job #2208459)

Utilizator georgeromanGeorge Roman georgeroman Data 29 mai 2018 21:15:06
Problema Algoritmul Bellman-Ford Scor 25
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <queue>

#define INF 0x3f3f3f3f

struct Edge {
  int from, to, cost;
  Edge(int from, int to, int cost): from(from), to(to), cost(cost) {}
};

int main() {
  std::ifstream in("bellmanford.in");
  std::ofstream out("bellmanford.out");
  
  int n, m;
  in >> n >> m;
  
  std::vector<std::vector<Edge>> graph;
  std::vector<int> dist;
  std::vector<int> pred;
  graph.reserve(n);
  dist.reserve(n);
  pred.reserve(n);
  for (int i = 0; i < n; i++) {
    graph.push_back(std::vector<Edge>());
    dist.push_back(INF);
    pred.push_back(-1);
  }
  std::queue<Edge> q;
  for (int i = 0; i < m; i++) {
    int from, to, cost;
    in >> from >> to >> cost;
    graph[from - 1].push_back(Edge(from, to, cost));
    q.push(Edge(from, to, cost));
  }
  
  dist[0] = 0;
  for(int i = 0; i < n - 1 && !q.empty(); i++) {
    std::vector<Edge> edges;
    while (!q.empty()) {
      edges.push_back(q.front());
      q.pop();
    }
    for (Edge& curr : edges) {
      if (dist[curr.to - 1] > dist[curr.from - 1] + curr.cost) {
        dist[curr.to - 1] = dist[curr.from - 1] + curr.cost;
        pred[curr.to - 1] = curr.from;
        for (Edge& e : graph[curr.to - 1]) {
          q.push(e);
        }
      }
    }
  }
  
  for (int i = 0; i < n; i++) {
    for (Edge& e : graph[i]) {
      if (dist[e.to - 1] > dist[e.from - 1] + e.cost) {
        out << "Ciclu negativ!";
        return 0;
      }
    }
  }
  
  for (int i = 1; i < n; i++) {
    out << dist[i] << " ";
  }
  
  return 0;
}