Cod sursa(job #3377290)

Utilizator nstefanNeagu Stefan nstefan Data 22 noiembrie 2026 20:04:40
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#include <climits>
using namespace std;

#ifdef INFOARENA
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define cin fin
#define cout fout
#endif

struct Neighbor {
  int id;
  int cost;
};

using Graph = vector<vector<Neighbor>>;

pair<vector<int>, bool> bellmanford(const Graph& g, int startNode) {
  vector<int> distances(g.size(), INT_MAX);
  distances[startNode] = 0;

  //// compute shortest distance
  for (int iteration = 1; iteration <= g.size() - 1; iteration++) {

    for (int node = 0; node < g.size(); node++) {
      if (distances[node] == INT_MAX) continue;

      for (auto neigh : g[node]) {
        distances[neigh.id] = min(distances[neigh.id], distances[node] + neigh.cost);
      }
    }

  }

  /// negative cycle detection
  bool hasCycle = false;
  for (int node = 0; node < g.size(); node++) {
    if (distances[node] == INT_MAX) continue;

    for (auto neigh : g[node]) {
      if (distances[node] + neigh.cost < distances[neigh.id]) {
        hasCycle = true;
        break;
      }
    }
  }

  return { std::move(distances), hasCycle };
}

int main() {
  int N, M; cin >> N >> M;
  Graph g(N + 1);
  for (int i = 0; i < M; i++) {
    int from, to, cost; cin >> from >> to >> cost;
    g[from].push_back({ to, cost });
  }

  /// belman ford
  auto [distances, hasCycle] = bellmanford(g, 1);

  if (hasCycle) {
    cout << "Ciclu negativ!";
  } else {
    for (int i = 2; i <= N; i++)
      cout << distances[i] << ' ';
  }
}