Cod sursa(job #515241)

Utilizator feelshiftFeelshift feelshift Data 20 decembrie 2010 20:41:02
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
// http://infoarena.ro/problema/bellmanford
#include <fstream>
#include <vector>
#include <list>
using namespace std;


#define INFINITY 0x3f3f3f3f
#define location first
#define cost second
int nodes,edges;

vector< list< pair<int,int> > > graph;
vector<int> dist;

void read();
bool bellmanFord(int startNode);
void write(bool cycle);

int main() {
	read();

	write(bellmanFord(1));


	return (0);
}

void read() {
	ifstream in("bellmanford.in");
	int from,to,Cost;

	in >> nodes >> edges;
	graph.resize(nodes+1);
	dist.resize(nodes+1);

	for(int i=1;i<=edges;i++) {
		in >> from >> to >> Cost;

		graph.at(from).push_back(make_pair(to,Cost));
	}

	in.close();
}

bool bellmanFord(int startNode) {
	dist.assign(nodes+1,INFINITY);
	dist.at(startNode) = 0;

	list< pair<int,int> >::iterator neighbour;

	for(int i=1;i<nodes;i++) {
		for(int currentNode=1;currentNode<=nodes;currentNode++)
			for(neighbour=graph.at(currentNode).begin();
				neighbour!=graph.at(currentNode).end();
				neighbour++)
				if(dist.at(currentNode) + neighbour->cost < dist.at(neighbour->location))
					dist.at(neighbour->location) = dist.at(currentNode) + neighbour->cost;
	}

	for(int i=1;i<nodes;i++) {
		for(int currentNode=1;currentNode<=nodes;currentNode++)
			for(neighbour=graph.at(currentNode).begin();
				neighbour!=graph.at(currentNode).end();
				neighbour++)
				if(dist.at(currentNode) + neighbour->cost < dist.at(neighbour->location))
					return true;	// exista ciclu negativ
	}

	return false;
}

void write(bool cycle) {
	ofstream out("bellmanford.out");

	if(cycle)
		out << "Ciclu negativ!\n";
	else
		for(int i=2;i<=nodes;i++)
			out << dist.at(i) << " ";

	out.close();
}