Cod sursa(job #2655223)

Utilizator PaulTPaul Tirlisan PaulT Data 3 octombrie 2020 17:20:16
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 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);
	VI cnt = VI(n + 1);
	queue<int> Q;
	VB inQ = VB(n + 1);
	
	d[x] = 0;
	Q.emplace(x);
	inQ[x] = true;
	cnt[x]++;
	while (!Q.empty())
	{
		x = Q.front();
		Q.pop();
		inQ[x] = false;
		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;
				if (!inQ[y])
				{
					Q.emplace(y);
					inQ[y] = true;
					cnt[x]++;
					if (cnt[x] == n)
						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);
	}
}