Cod sursa(job #2111953)

Utilizator theodor.vladTheodor Vlad theodor.vlad Data 22 ianuarie 2018 20:16:00
Problema Algoritmul Bellman-Ford Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF 3333

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

struct edge
{
	int nod, c;
};

vector <edge> a[50005];
vector <int> dmin;
vector <int> nr;

queue <int> q;

int n, m, k;

void read();
bool Bellman_Ford();
int cost(int x, int y);
void write();

int main()
{
	read();
	write();

	return 0;
}

void read()
{
	int i, x;
	edge muchie;
	muchie.nod = muchie.c = 0;

	fin >> n >> m;

	for (i = 1; i <= n + 1; i++)
	{
		a[i].push_back(muchie);
		nr.push_back(0);
		dmin.push_back(INF);
	}

	dmin[1] = 0;

	for (i = 1; i <= m; i++)
	{
		fin >> x >> muchie.nod >> muchie.c;
		a[x].push_back(muchie); a[x][0].c++;
	}

	q.push(1);

	for (i = 1; i <= a[1][0].c; i++)
	{
		dmin[a[1][i].nod] = a[1][i].c;
		q.push(a[1][i].nod);
	}
}

bool Bellman_Ford()
{
	int i, x;
	bool negative_circuit = false;

	while (!q.empty() && !negative_circuit)
	{
		x = q.front(); q.pop();

		for (i = 1; i <= a[x][0].c; i++)
			if (dmin[a[x][i].nod] > dmin[x] + cost(x, a[x][i].nod))
			{
				dmin[a[x][i].nod] = dmin[x] + cost(x, a[x][i].nod);
				nr[a[x][i].nod]++;
				
				if (nr[a[x][i].nod] == n)
				{
					negative_circuit = true; break;
				}
				q.push(a[x][i].nod);
			}
	}

	return negative_circuit;
}

void write()
{
	if (Bellman_Ford())
		fout << "Ciclu negativ!\n";
	else
	{
		for (int i = 2; i <= n; i++)
			fout << dmin[i] << ' ';
		fout << '\n';
	}
}

int cost(int x, int y)
{
	for (int i = 1; i <= a[x][0].c; i++)
		if (a[x][i].nod == y)
			return a[x][i].c;
}