Cod sursa(job #2533551)

Utilizator radustn92Radu Stancu radustn92 Data 29 ianuarie 2020 11:58:46
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;

struct edge {
	int from, to, cost;
};

int N, M;
vector<edge> allEdges;

void read() {
	scanf("%d%d", &N, &M);
	int x, y, c;
	for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
		scanf("%d%d%d", &x, &y, &c);
		allEdges.push_back({x, y, c});
	}
}

void solve() {
	vector<int> D(N + 1, INF);
	D[1] = 0;
	int lastImprovedNode = 1;
	for (int step = 0; step < N && lastImprovedNode; step++) {
		lastImprovedNode = -1;
		for (auto& candidateEdge : allEdges) {
			if (D[candidateEdge.from] != INF && D[candidateEdge.to] > D[candidateEdge.from] + candidateEdge.cost) {
				lastImprovedNode = candidateEdge.to;
				D[candidateEdge.to] = D[candidateEdge.from] + candidateEdge.cost;
			}
		}
	}

	if (lastImprovedNode != -1) {
		printf("Ciclu negativ!\n");
	} else {
		for (int node = 2; node <= N; node++) {
			printf("%d ", D[node]);
		}
		printf("\n");
	}
}

int main() {
	freopen("bellmanford.in", "r", stdin);
	freopen("bellmanford.out", "w", stdout);

	read();
	solve();
	return 0;
}