Cod sursa(job #526564)
// http://infoarena.ro/problema/dijkstra
#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;
int dist[50001];
priority_queue< pair<int,int>, vector< pair<int,int> >, greater< pair<int,int> > > myHeap; // wtf?!?
void read();
void dijkstra(int startNode);
bool isInf(int number) { return (number == INFINITY); }
void write();
int main() {
read();
dijkstra(1);
write();
return (0);
}
void read() {
ifstream in("dijkstra.in");
int from,to,cost;
in >> nodes >> edges;
graph.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();
}
void dijkstra(int startNode) {
myHeap.push(make_pair(0,startNode)); // se introduce nodul de pornire in heap
memset(dist,INFINITY,50001);
dist[startNode] = 0;
pair<int,int> currentNode;
list< pair<int,int> >::iterator neighbour;
while(!myHeap.empty()) {
currentNode = myHeap.top(); // se extrage minimul
myHeap.pop(); // se elimina nodul extras din lista
for(neighbour=graph.at(currentNode.location).begin(); neighbour!=graph.at(currentNode.location).end();neighbour++)
if(dist[neighbour->location] > dist[currentNode.location] + neighbour->cost) {
dist[neighbour->location] = dist[currentNode.location] + neighbour->cost;
// se adauga nodul in lista
myHeap.push(make_pair(dist[neighbour->location],neighbour->location));
}
}
}
void write() {
ofstream out("dijkstra.out");
for(int i=2;i<=nodes;i++)
if(dist[i] != INFINITY)
out << dist[i] << " ";
else
out << "0 ";
out.close();
}