Cod sursa(job #2843259)

Utilizator game_difficultyCalin Crangus game_difficulty Data 2 februarie 2022 11:31:00
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
#include <queue>
	
using namespace std;
	
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");

const int INF = 50e6;
vector<pair<int, int>> graf[50005];
int dist[50005];
int f[50005];
	
int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y, d;
		cin >> x >> y >> d;
		graf[x].push_back({ y, d });
	}
	for (int i = 2; i <= n; i++) {
		dist[i] = INF;
	}
	priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
	q.push({ 0, 1 });
	while (!q.empty()) {
		int now = q.top().second;
		q.pop();
		for (auto i : graf[now]) {
			if (dist[now] + i.second < dist[i.first]) {
				dist[i.first] = dist[now] + i.second;
				f[i.first]++;
				if (f[i.first] > m) {
					cout << "Ciclu negativ!";
					return -0;
				}
				q.push({ dist[i.first], i.first });
			}
		}
	}
	for (int i = 2; i <= n; i++) {
		cout << dist[i] << ' ';
	}
	return 0;
}