Cod sursa(job #527609)

Utilizator feelshiftFeelshift feelshift Data 31 ianuarie 2011 22:12:21
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
// http://infoarena.ro/problema/dijkstra
#include <fstream>
#include <list>
#include <queue>
using namespace std;

#define INFINITY 0x3f3f3f3f
#define maxSize 50001
#define location second
#define cost first

int nodes;
int dist[maxSize];
list< pair<int,int> > graph[maxSize];
priority_queue< pair<int,int>, vector< pair<int,int> >, greater< pair<int,int> > > myHeap;

void read();
void dijkstra(int startNode);
void write();

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

	return (0);
}

void read() {
	ifstream in("dijkstra.in");
	int edges,from,to,cost;

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

		graph[from].push_back(make_pair(cost,to));	// graful este orientat
	}

	in.close();
}

void dijkstra(int startNode) {
	memset(dist,INFINITY,(nodes+1)*sizeof(int));
	dist[startNode] = 0;

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

	myHeap.push(make_pair(0,startNode));	// se introduce nodul de pornire in heap

	while(!myHeap.empty()) {
		currentNode = myHeap.top();	// se extrage minimul
		myHeap.pop();	// se elimina nodul extras

		for(neighbour=graph[currentNode.location].begin();neighbour!=graph[currentNode.location].end();neighbour++)
			// daca se poate imbunatatii costul
			if(dist[neighbour->location] > dist[currentNode.location] + neighbour->cost) {
				dist[neighbour->location] = dist[currentNode.location] + neighbour->cost;	// se imbunatateste
				myHeap.push(make_pair(dist[neighbour->location],neighbour->location));	// se introduce in heap
			}
	}
}

void write() {
	ofstream out("dijkstra.out");

	for(int i=2;i<=nodes;i++)
		if(dist[i] == INFINITY)
			out << "0 ";
		else
			out << dist[i] << " ";

	out.close();
}