Pagini recente » Cod sursa (job #901576) | Cod sursa (job #362594) | Cod sursa (job #976317) | Cod sursa (job #1895309) | Cod sursa (job #515609)
Cod sursa(job #515609)
// http://infoarena.ro/problema/dijkstra
#include <fstream>
#include <algorithm>
#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;
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);
dist.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
dist.assign(nodes+1,INFINITY);
dist.at(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.at(neighbour->location) > dist.at(currentNode.location) + neighbour->cost) {
dist.at(neighbour->location) = dist.at(currentNode.location) + neighbour->cost;
// se adauga nodul in lista
myHeap.push(make_pair(dist.at(neighbour->location),neighbour->location));
}
}
}
void write() {
ofstream out("dijkstra.out");
replace_if(dist.begin(),dist.end(),isInf,0);
for(int i=2;i<=nodes;i++)
out << dist.at(i) << " ";
out.close();
}