Cod sursa(job #2517517)

Utilizator PaulTPaul Tirlisan PaulT Data 3 ianuarie 2020 17:52:53
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

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

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

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

int main()
{
	Read();
	BellmanFord(1, d);
	Write();
}

void BellmanFord(int x, VI& d)
{
	queue<int> Q;
	VB inQ = VB(n + 1);
	VI nr = VI(n + 1);
	d = VI(n + 1, Inf);
	
	d[x] = 0;
	Q.emplace(x);
	inQ[x] = true;
	nr[x]++;
	int y, w;
	while (!Q.empty())
	{
		x = Q.front();
		Q.pop();
		inQ[x] = false;
		for (const PI& p : G[x])
		{
			y = p.first;
			w = p.second;
			if (d[y] > d[x] + w)
			{
				d[y] = d[x] + w;
				if (!inQ[y])
				{
					Q.emplace(y);
					inQ[y] = true;
					nr[y]++;
					if (nr[y] == n)
					{
						negativ = true;
						return;
					}
				}
			}
		}
	}
}

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

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);
	}
}