Cod sursa(job #2611479)

Utilizator cristi1616Olaru Cristian cristi1616 Data 6 mai 2020 22:34:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

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

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;

  void read_input() {
    ifstream fin("bellmanford.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() {
    if (BellmanFord(source, d)) {
      ofstream fout("bellmanford.out");
      fout << "Ciclu negativ!";
    } else {
      print_output();
    }
  }

  bool BellmanFord(int source, vector<int> &d) {
    vector<int> used(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
      d[i] = oo;
    }
    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;
          q.push(neighbour);
        }
      }
    }
    return false;
  }
  void print_output() {
    ofstream fout("bellmanford.out");
    for (int i = 1; i <= n; ++i) {
      if (i == source) {
        continue;
      }
      if (d[i] == 0) {
        fout << 0 << " ";
        continue;
      }
      fout << d[i] << " ";
    }
    fout << "\n";
  }
};

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