Cod sursa(job #2772594)

Utilizator rARES_4Popa Rares rARES_4 Data 1 septembrie 2021 19:12:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m;
vector<pair<int, int>>adiacenta[50001];
queue<int>q;
int costuri[50001];
int entered_queue[50001];
int main()
{
	f >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int nr1, nr2, cost;
		f >> nr1 >> nr2 >> cost;
		adiacenta[nr1].push_back({ nr2,cost });
	}

	for (int i = 1; i <= n; i++)
	{
		costuri[i] = INT_MAX;
	}
	costuri[1] = 1;
	entered_queue[1] = 1;
	q.push(1);
	while (!q.empty())
	{
		int nod_curent = q.front();
		q.pop();

		for (auto x : adiacenta[nod_curent])
		{
			if (costuri[x.first] > costuri[nod_curent] + x.second)
			{
				costuri[x.first] = costuri[nod_curent] + x.second;
				q.push(x.first);
				entered_queue[x.first]++;
			}
			if (entered_queue[x.first] > n)
			{
				g << "Ciclu negativ!";
				return 0;
			}
		}
	}
	for (int i = 2; i <= n; i++)
	{
		if (costuri[i] == INT_MAX)
		{
			g << "0 ";
		}
		else
			g << costuri[i] - 1 << " ";
	}
}