Cod sursa(job #2772592)

Utilizator rARES_4Popa Rares rARES_4 Data 1 septembrie 2021 19:04:03
Problema Algoritmul Bellman-Ford Scor 75
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 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<pair<int,int>>q;
int costuri[50000];
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,1 });
	while (!q.empty())
	{
		int nod_curent = q.front().first;
		int cost_curent = q.front().second;
		q.pop();

		for (auto x : adiacenta[nod_curent])
		{
			if (costuri[x.first] > cost_curent + x.second)
			{
				costuri[x.first] = cost_curent + x.second;
				q.push({ x.first,costuri[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 << " ";
	}
}