Cod sursa(job #3212394)

Utilizator leelcheeseCiovnicu Denis leelcheese Data 11 martie 2024 18:05:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 50005
#define kmax 250005
#define MOD 1999999973
#define INF 2012345678
#define ll long long
using namespace std;
//#define fin cin
//#define fout cout

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

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

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

int main()
{
	int i, x, y, c;
	bool cicluNeg;
	fin >> n >> m;
	for (i = 1; i <= m; i++)
	{
		fin >> x >> y >> c;
		L[x].push_back({ y, c });
	}
	
	cicluNeg = BellmanFord();
	if (cicluNeg)
		fout << "Ciclu negativ!\n";
	else
	{
		for (i = 2; i <= n; i++)
			fout << d[i] << " ";
		fout << "\n";
	}
	fin.close();
	fout.close();
	return 0;
}