Pagini recente » Cod sursa (job #660785) | Cod sursa (job #422522) | Cod sursa (job #1234483) | Cod sursa (job #3251173) | Cod sursa (job #3272295)
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h> // Pentru INT_MAX
#include <fstream>
using namespace std;
vector<int> bellman_ford(const vector<vector<pair<int, int>>>& graph, int n, int start) {
vector<int> dist(n + 1, 1e9);
vector<bool> visited(n + 1, false);
vector<int> count(n + 1, 0);
queue<int> q;
dist[start] = 0;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
visited[node] = false;
for (auto [neigh, w] : graph[node]) {
if (dist[node] + w < dist[neigh]) {
dist[neigh] = dist[node] + w;
if (!visited[neigh]) {
q.push(neigh);
visited[neigh] = true;
count[neigh]++;
if (count[neigh] > n) {
cout << "Ciclu negativ!";
return {};
}
}
}
}
}
return dist;
}
int main()
{
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
fin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; i++) {
int a, b, c;
fin >> a >> b >> c;
graph[a].emplace_back(b, c);
}
vector<int> result = bellman_ford(graph, n, 1);
if (!result.empty()) {
for (int i = 2; i <= n; i++) {
fout << result[i] << ' ';
}
fout << '\n';
}
return 0;
}