Cod sursa(job #2670167)

Utilizator retrogradLucian Bicsi retrograd Data 9 noiembrie 2020 11:40:23
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <bits/stdc++.h>

using namespace std;

class InParser {
private:
  FILE* fin;
  char* buff;
  int sp;

  char read_ch() {
    ++sp;
    if (sp == 4096) {
      sp = 0;
      fread(buff, 1, 4096, fin);
    }
    return buff[sp];
  }

public:
  InParser(const char* nume) {
    fin = fopen(nume, "r");
    buff = new char[4096]();
    sp = 4095;
  }

  InParser& operator >> (int& n) {
    char c;
    while (!isdigit(c = read_ch()) && c != '-');
    int sgn = 1;
    if (c == '-') {
      n = 0;
      sgn = -1;
    } else {
      n = c - '0';
    }
    while (isdigit(c = read_ch())) {
      n = 10 * n + c - '0';
    }
    n *= sgn;
    return *this;
  }
};


struct Edge {
  int a, b, c;
  bool operator<(const Edge& oth) const {
    return make_tuple(a < b, a, b, c) <
      make_tuple(oth.a < oth.b, oth.a, oth.b, oth.c);
  }
};

int main() {
  InParser cin("bellmanford.in");
  ofstream cout("bellmanford.out");

  int n, m; cin >> n >> m;
  vector<Edge> es(m);
  for (int i = 0; i < m; ++i) {
    auto& e = es[i];
    cin >> e.a >> e.b >> e.c; --e.a; --e.b;
  }
  sort(es.begin(), es.end());


  vector<int> dist(n, 1e9), prev(n, -1);
  auto relax = [&](const Edge& e) {
    if (dist[e.b] <= dist[e.a] + e.c)
      return false;

    dist[e.b] = dist[e.a] + e.c;
    prev[e.b] = e.a;
    return true;
  };

  vector<int> deg(n), qc; qc.reserve(n);
  auto has_cycle = [&]() {
    fill(deg.begin(), deg.end(), 0);
    for (int i = 0; i < n; ++i) {
      if (prev[i] != -1)
        deg[prev[i]] += 1;
    }
    qc.clear();
    for (int i = 0; i < n; ++i)
      if (deg[i] == 0)
        qc.push_back(i);
    for (int i = 0; i < (int)qc.size(); ++i) {
      int node = qc[i];
      if (prev[node] != -1 && --deg[prev[node]] == 0)
        qc.push_back(prev[node]);
    }
    return (int)qc.size() < n;
  };

  dist[0] = 0;
  int ch = 1;
  while (ch--) {
    for (const auto& e : es)
      ch |= relax(e);
    if (has_cycle()) {
      cout << "Ciclu negativ!" << endl;
      return 0;
    }
  }

  for (int i = 1; i < n; ++i)
    cout << dist[i] << " ";
  cout << endl;

  return 0;
}