Cod sursa(job #515621)

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

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

vector< list< pair<int,int> > > graph;
vector<int> dist;
vector<bool> inQueue;
	queue<int> myQueue;
priority_queue< pair<int,int>, vector< pair<int,int> >, greater< pair<int,int> > > myHeap;

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);
	inQueue.resize(nodes+1);

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

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

	in.close();
}

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

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

	for(int i=1;i<=nodes;i++) {
		myQueue.push(i);
		inQueue.at(i) = true;
	}

	while(!myQueue.empty()) {
		currentNode = myQueue.front();
		myQueue.pop();
		inQueue.at(currentNode) = false;

		for(neighbour=graph.at(currentNode).begin();
			neighbour!=graph.at(currentNode).end();
			neighbour++)
			if(dist.at(neighbour->location) > dist.at(currentNode) + neighbour->cost) {
				dist.at(neighbour->location) = dist.at(currentNode) + neighbour->cost;
				if(!inQueue.at(neighbour->location))
					myQueue.push(neighbour->location);
			}
	}

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

	return true;
}

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

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

	out.close();
}