Cod sursa(job #3221909)

Utilizator alex210046Bratu Alexandru alex210046 Data 8 aprilie 2024 14:57:23
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#include <unordered_map>
#defe nmax 50006
#defe MOD 1999999973
#defe INF 2012345678
#defe ll long long
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m;
vector <pair <int, int>> L[nmax];
queue <int> q;
bitset <nmax> viz;
int d[nmax], cnt[nmax];

bool BellmanFord(int k) {
	int x, cost;
	for (int i = 1; i <= n; i++)
		d[i] = INF;
	q.push(k);
	d[k] = 0;
	viz[k] = 1;
	while (!q.empty()) {
		k = q.front();
		q.pop();
		viz[k] = 0;
		for (auto w : L[k]) {
			x = w.second;
			cost = w.first;
			if (d[x] > d[k] + cost) {
				d[x] = d[k] + cost;
				if (viz[x] == 0) {
					viz[x] = 1;
					q.push(x);
					cnt[x]++;
					if (cnt[x] > n)
						return 1;
				}
			}
		}
	}

	return 0;
}

int main()
{
	int i, x, y, cost;
	f >> n >> m;
	for (i = 1; i <= m; i++) {
		f >> x >> y >> cost;
		L[x].push_back({ cost, y });
	}

	if (BellmanFord(1))
		g << "Ciclu negativ!";
	else {
		for (i = 2; i <= n; i++)
			g << d[i] << " ";
		g << "\n";
	}

	return 0;
}