Cod sursa(job #3325126)

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

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const long long INF = 1000000000;
const int MAXN = 50003;

vector<vector<pair<int, int>>> g(MAXN);

int main() {

	int n, m;
	in >> n >> m;
	
	for(int i = 1; i <= m; i++) {
		int x, y, cost;
		in >> 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;
	in_queue[1] = true;
	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++) {
		out << dist[i] << ' ';
	}

	return 0;
}