Cod sursa(job #515922)

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

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

vector< list< pair<int,int> > > graph;
vector<int> dist;
vector<bool> visit;
vector<int> timesVisited;
queue<int> myQueue;

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


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

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

	myQueue.push(startNode);
	
	while(!myQueue.empty()) {
		currentNode = myQueue.front();

		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(!visit.at(neighbour->location)) {
					timesVisited.at(neighbour->location)++;

					if(timesVisited.at(neighbour->location) > nodes)
						return false;
				}

				myQueue.push(neighbour->location);
				visit.at(neighbour->location) = true;
			}

			visit.at(currentNode) = false;
			myQueue.pop();
	}

	return true;
}

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

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

	out.close();
}