Cod sursa(job #2655221)

Utilizator PaulTPaul Tirlisan PaulT Data 3 octombrie 2020 17:15:32
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

using PI = pair<int, int>;
using VP = vector<PI>;
using VVP = vector<VP>;
using VI = vector<int>;
using VB = vector<bool>;

const int Inf = 0x3f3f3f3f;
int n, m;
VVP G;
VI d;

void Read();
bool BellmanFord(int x, VI& d);

int main()
{
	Read();
	ofstream fout("bellmanford.out");
	if (BellmanFord(1, d))
		fout << "Ciclu negativ!";
	else
		for (int i = 2; i <= n; i++)
			fout << d[i] << ' ';
}

bool BellmanFord(int x, VI& d)
{
	d = VI(n + 1, Inf);
	d[x] = 0;
	for (int i = 1; i < n; i++)
		for (int x = 1; x <= n; x++)
			for (const PI& p : G[x])
			{
				int y = p.first;
				int w = p.second;
				if (d[y] > d[x] + w)
					d[y] = d[x] + w;
			}
	
	for (int x = 1; x <= n; x++)
		for (const PI& p : G[x])
		{
			int y = p.first;
			int w = p.second;
			if (d[y] > d[x] + w)
				return true;
		}
	return false;
}

void Read()
{
	ifstream fin("bellmanford.in");
	fin >> n >> m;
	G = VVP(n + 1);
	
	int x, y, w;
	for (int i = 0; i < m; i++)
	{
		fin >> x >> y >> w;
		G[x].emplace_back(y, w);
	}
}