Cod sursa(job #2199773)

Utilizator WebDesignbyTMGhiorghiu Ioan-Viorel WebDesignbyTM Data 29 aprilie 2018 00:04:32
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#define DM 50001
#define inf 0x3f3f3f3f
#define x first
#define y second
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

ifstream fi ("bellmanford.in");
ofstream fo ("bellmanford.out");
bool ncycle;
int n, m, a, b, c, dst[DM], used[DM];
queue <int> q;
vector <pair <int, int> > v[DM];

int main()
{
	fi >> n >> m;
	memset(dst, inf, sizeof(dst));
	for (int i = 1; i <= m; ++i)
	{
		fi >> a >> b >> c;
		v[a].push_back({b, c});
	}
	dst[1] = 0;
	q.push(1);
	while (!q.empty() && !ncycle)
	{
		a = q.front();
		q.pop();
		for (auto i:v[a])
			if (dst[i.x] > dst[a] + i.y)
			{
				if (used[i.x] == n - 1)
					ncycle = 1;
				else
				{
					++used[i.x];
					q.push(i.x);
					dst[i.x] = dst[a] + i.y;
				}
			}
	}
	if (ncycle)
	{
		fo << "Ciclu negativ!";
		return 0;
	}
	for (int i = 2; i <= n; ++i)
		fo << dst[i] << ' ';
	return 0;
}