Cod sursa(job #3377378)

Utilizator nstefanNeagu Stefan nstefan Data 23 noiembrie 2026 03:43:29
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
#include <climits>
#include <queue>
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);
  vector<int> popped(g.size());
  distances[startNode] = 0;

  queue<int> q;
  vector<bool> inQueue(g.size());

  q.push(startNode);
  inQueue[startNode] = true;

  while (!q.empty()) {
    int node = q.front(); q.pop();
    inQueue[node] = false;

    if (popped[node]++ == g.size())
      return { std::move(distances), true };

    for (auto neigh : g[node])
      if (distances[node] + neigh.cost < distances[neigh.id]) {
        distances[neigh.id] = distances[node] + neigh.cost;
        if (!inQueue[neigh.id]) { q.push(neigh.id); inQueue[neigh.id] = true; }
      }
  }

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

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] << ' ';
  }
}