Cod sursa(job #2611145)

Utilizator candulHoisan Stefan candul Data 6 mai 2020 14:51:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.41 kb
// Copyright 2018 Popescu Alexandru Gabriel <[email protected]>
// Copyright 2017 Darius Neatu <[email protected]>

// BellmanFord
// O(m * n)

#include <bits/stdc++.h>

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

using namespace std;

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

private:
  int n, m;
  int source;

  vector<pair<int, int>> adj[NMAX];

  queue<int> q;
  vector<int> d;
  vector<int> p;

  void read_input() {
    cin >> n >> m;

    d.resize(n + 1);

    p.resize(n + 1);

    source = 1;

    for (int i = 1; i <= m; ++i) {
      int x, y, c;
      cin >> x >> y >> c;
      adj[x].push_back({y, c});
    }
  }

  void get_result() {
    if (BellmanFord(source, d, p)) {
      cout << "Ciclu negativ!";
    } else {
      print_output();
    }
  }

  bool BellmanFord(int source, vector<int> &d, vector<int> &p) {

    vector<int> used(n + 1, 0);

    for (int i = 1; i <= n; ++i) {
      d[i] = oo;
      p[i] = NO_PARENT;
    }
    p[source] = 0;
    d[source] = 0;
    q.push(source);

    while (!q.empty()) {
      int node = q.front();
      q.pop();

      ++used[node];
      if (used[node] == n) {
        return true;
      }

      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;
          p[neighbour] = node;
          q.push(neighbour);
        }
      }
    }
    return false;
  }

  vector<int> rebuild_path(int node, vector<int> &p) {
    if (p[node] == NO_PARENT) {
      return {};
    }

    vector<int> path;
    for (; node != 0; node = p[node]) {
      path.push_back(node);
    }
    reverse(path.begin(), path.end());

    return path;
  }

  void print_output() {
    for (int i = 1; i <= n; ++i) {
      if (i == source) {
        continue;
      }
      if (d[i] == 0) {
        continue;
      }
      cout << d[i] << " ";
    }
  }
};

int main() {

  auto cin_buff = cin.rdbuf();
  auto cout_buff = cout.rdbuf();

  ifstream fin("bellmanford.in");
  ofstream fout("bellmanford.out");
  cin.rdbuf(fin.rdbuf());
  cout.rdbuf(fout.rdbuf());

  Task *task = new Task();
  task->solve();
  delete task;

  cin.rdbuf(cin_buff);
  cout.rdbuf(cout_buff);

  return 0;
}