Cod sursa(job #2670305)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 9 noiembrie 2020 17:27:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

vector <pair <int, int>> v[50001];

queue <int> q;
bool b[50001];
int d[50001], cnt[50001];

bool bf(int n)
{
	int na, i, x, y;
	for (i = 1; i<=n; i++)
		d[i] = 1<<30;
	d[1] = 0;
	b[1] = 1;
	q.push(1);
	
	while (q.empty() == 0)
	{
		na = q.front();
		q.pop();
		b[na] = 0;
		
		for (i = 0; i<v[na].size(); i++)
		{
			x = v[na][i].first;
			y = v[na][i].second;
			if (d[x] > d[na] + y)
			{
				d[x] = d[na] + y;
				if (b[x] == 0)
				{
					b[x] = 1;
					cnt[x]++;
					if (cnt[x] == n)
						return 0;
					q.push(x);
				}
			}
		}
	}
	return 1;
}

int main()
{
	int i, n, m, x, y, z;
	fin >> n >> m;
	for (i = 1; i<=m; i++)
	{
		fin >> x >> y >> z;
		v[x].push_back({y, z});
	}
	if (bf(n) == 0)
		fout << "Ciclu negativ!";
	else
		for (i = 2; i<=n; i++)
			fout << d[i] << ' ';
	return 0;
}