Cod sursa(job #3300761)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 18 iunie 2025 20:18:00
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 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;

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

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

struct Edge {
	int a, b, c;
};

int n, m;
vector<Edge> edges;
int distances[MAXN];

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

void Solve() {
	memset(distances, INF, sizeof(distances));
	distances[1] = 0;

	for (int i = 0; i < n; i++) {
		for (Edge edge : edges) {
			if (distances[edge.a] == INF) {
				continue;
			}
			if (distances[edge.b] > distances[edge.a] + edge.c) {
				if (i == n - 1) {
					fout << "Ciclu negativ!\n";
					return;
				}
				distances[edge.b] = distances[edge.a] + edge.c;
			}
		}
	}

	for (int i = 2; i <= n; i++) {
		if (distances[i] == INF) fout << -1 << ' ';
		else fout << distances[i] << ' ';
	}
	fout << '\n';
}


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