Cod sursa(job #1666446)

Utilizator andreioneaAndrei Onea andreionea Data 28 martie 2016 00:49:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <tuple>
#include <limits>
#include <algorithm>

using Vertex = int;
using Distance = uint64_t;

using Edge = std::tuple<Vertex, Vertex, Distance>;

void BellmanFord(std::vector<Distance>& distances, const std::vector<Edge>& graph, int N)
{
	auto changed = true;
	for (auto i = 0; i < N && changed; ++i)
	{
		changed = false;
		for (const auto& edge : graph)
		{
			Vertex u, v;
			Distance d;
			std::tie(u, v, d) = edge;
			if ((distances[u - 1] + d) < distances[v - 1])
			{
				changed = true;
				distances[v - 1] = distances[u - 1] + d;
			}
		}
	}
}
int main()
{
	std::ifstream fin("dijkstra.in");
	int N, M;
	fin >> N >> M;
	std::vector<Distance> distances(N, std::numeric_limits<Distance>::max() - 1001);
	std::vector<Edge> edges(M);
	for (int i = 0; i < M; ++i)
	{
		Vertex u, v;
		Distance d;
		fin >> u >> v >> d;
		edges[i] = std::make_tuple(u, v , d);
	}
	fin.close();
	distances[0] = 0;
	BellmanFord(distances, edges, N);
	distances.erase(distances.begin());
	std::ofstream fout("dijkstra.out");
	for (const auto d : distances)
	{
		if (d == std::numeric_limits<Distance>::max() - 1001)
			fout << 0 << " ";
		else
			fout << d << " ";
	}
	fout.close();
	return 0;
}