Cod sursa(job #3300792)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 19 iunie 2025 02:22:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;

#define fast_io ios::sync_with_stdio(0); cin.tie(0); do{}while(0)
typedef long long ll;

const int INF = 0x3f3f3f3f;
const int MAXN = 5e4 + 5;

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

struct Edge {
	int dest, c;
};

int n, m;
vector<Edge> graph[MAXN];
int realax[MAXN];
int distances[MAXN];
bool inQueue[MAXN];
queue<Edge> q;

void ReadData() {
	fin >> n >> m;
	int a, b, c;
	for (int i = 0; i < m; i++) {
		fin >> a >> b >> c;
		graph[a].push_back({b, c});
	}
}

bool BellmanFord() {
	memset(distances, INF, sizeof(distances));
	distances[1] = 0;
	inQueue[1] = true;
	q.push({1, 0});

	while (!q.empty()) {
		Edge curr = q.front();
		inQueue[curr.dest] = false;
		q.pop();

		for (Edge e : graph[curr.dest]) {
			if (distances[e.dest] <= distances[curr.dest] + e.c) {
				continue;
			}
			distances[e.dest] = distances[curr.dest] + e.c;

			if (!inQueue[e.dest]) {
				q.push({e.dest, distances[e.dest]});
				inQueue[e.dest] = true;
				realax[e.dest]++;
				if (realax[e.dest] > n) {
					return false;
				}
			}
		}
	}
	return true;
}

void Solve() {
	if (!BellmanFord()) {
		fout << "Ciclu negativ!\n";
		return;
	}
	for (int i = 2; i <= n; i++) {
		fout << distances[i] << ' ';
	}
	fout << '\n';
}

int main() {
		ReadData();
		Solve();
		return 0;
}