Cod sursa(job #1337717)

Utilizator alexb97Alexandru Buhai alexb97 Data 9 februarie 2015 13:45:09
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

#define DIM 50010
#define INF 0x3f3f3f3f

ifstream is("bellmanford.in");
ofstream os("bellmanford.out");

vector <vector<pair<int, int>>> g;
vector <int> d;
bitset <DIM> inQueue;
queue <int> q;
int n, m;
int cnt[DIM];
bool work;

void Read();
void Solve();
void Write();

int main()
{
	Read();
	Solve();
	if(!work)
		Write();
	is.close();
	os.close();
	return 0;
	
}

void Read()
{
	is >> n >> m;
	int x, y, z;
	g = vector<vector<pair<int, int>>>(n+1);
	d = vector<int>(n+1, INF);
	for(int i = 1; i <= m; ++i)
	{
		is >> x >> y >> z;
		g[x].push_back({y, z});
	}
}

void Solve()
{
	q.push(1);
	d[1] = 0;
	inQueue[1] = 1;
	int x;
	while(!q.empty())
	{
		x = q.front();
		inQueue[x] = 0;
		q.pop();
		for(const auto & y : g[x])
		{
			if(d[y.first] > d[x] + y.second)
			{
				d[y.first] = d[x] + y.second;
				if(!inQueue[y.first])
				{
					cnt[y.first]++;
					if(cnt[y.first] == n)
					{
						os << "Ciclu negativ!";
						work = true;
						return;
					}
					q.push(y.first);
					inQueue[y.first] = 1;
				}
			}
		} 
	}
}

void Write()
{
	for(int i = 2; i <= n; ++i)
	{
		os << d[i] << ' ';
	}
	return ;
}