Cod sursa(job #2894791)

Utilizator matthriscuMatt . matthriscu Data 28 aprilie 2022 13:24:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 50005

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

	int n, m;
	vector<pair<int, int>> G[NMAX];

	scanf("%d%d", &n, &m);

	for (int i = 1, x, y, c; i <= m; ++i) {
		scanf("%d%d%d", &x, &y, &c);
		G[x].push_back({y, c});
	}

	int dist[NMAX];
	memset(dist, 0x7F, sizeof(dist));
	dist[1] = 0;

	queue<int> q;
	q.push(1);

	int cnt_in_queue[NMAX] {};
	bool in_queue[NMAX];

	while (!q.empty()) {
		int curr = q.front();
		q.pop();
		in_queue[curr] = 0;

		for (const auto &[neigh, cost] : G[curr]) {
			if (dist[curr] + cost < dist[neigh]) {
				dist[neigh] = dist[curr] + cost;
				if (!in_queue[neigh]) {
					q.push(neigh);
					in_queue[neigh] = 1;
					if (++cnt_in_queue[curr] > n) {
						puts("Ciclu negativ!");
						return 0;
					}
				}
			}
		}
	}

	for (int i = 2; i <= n; ++i)
		printf("%d ", dist[i]);
	puts("");
}