Cod sursa(job #2892840)

Utilizator dream3rDavid Pop dream3r Data 23 aprilie 2022 18:48:27
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <climits>
std::ifstream f("bellmanford.in");
std::ofstream o("bellmanford.out");

std::vector<int>g[50005];
std::map<std::pair<int, int>, int>costs;
int nodes, edges;
std::vector<int>distances(50005, INT_MAX);
std::vector<int>visited(50005, 0);
bool cycle = false;

void bellman_ford(int start)
{
	distances[start] = 0;
	for (size_t node = 1; node < nodes; node++)
	{
		for (auto& edge : costs)
		{
			if (distances[edge.first.first] + edge.second < distances[edge.first.second])
			{
				//distances[edge.first.first] + edge.second < distances[edge.first.second]
				distances[edge.first.second] = distances[edge.first.first] + edge.second;
			}
		}
	}

	for (size_t node = 1; node < nodes; node++)
	{
		for (auto& edge : costs)
		{
			if (distances[edge.first.first] + edge.second < distances[edge.first.second])
			{
				//distances[edge.first.first] + edge.second < distances[edge.first.second]
				cycle = true;
				return;
			}
		}
	}


}

int main()
{
	f >> nodes >> edges;
	int i = edges;
	while (i--)
	{

		int start, to, cost;
		f >> start >> to >> cost;
		g[start].push_back(to);
		costs[std::make_pair(start, to)] = cost;
	}

	bellman_ford(1);

	if (cycle==true)
	{
		o << "Ciclu negativ!";
	}
	else {
		for (size_t i = 2; i <= nodes; i++)
		{
			o << distances[i] << " ";
		}
	}
	return 0;
}