Cod sursa(job #3325115)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 24 noiembrie 2025 20:11:45
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int main() {

	const int INF = 1e12;

	int n, m;
	cin >> n >> m;

	vector<vector<pair<int, int>>> g(n + 1);
	for(int i = 1; i <= m; i++) {
		int x, y, cost;
		cin >> x >> y >> cost;
		g[x].push_back({y, cost});
	}	

	// SPFA - Shortest Path Faster Algorithm

	queue<int> q;
	vector<long long> dist(n + 1, INF), seen(n + 1, 0);
	vector<bool> in_queue(n + 1, false);

	dist[1] = 0;
	q.push(1);
	while(!q.empty()) {
		int node = q.front();
		q.pop();
		in_queue[node] = false;
		for(auto [son, cost] : g[node]) {
			if(dist[node] + cost < dist[son]) {
				dist[son] = dist[node] + cost;
				if(!in_queue[son]) {
					q.push(son);
					in_queue[son] = true;
					seen[son]++;
					if(seen[son] > n) {
						cout << "Ciclu negativ!\n";
						return 0;
					}
				}
			}
		}
	}

	for(int i = 2; i <= n; i++) {
		cout << dist[i] << ' ';
	}

	return 0;
}