Pagini recente » Cod sursa (job #1759652) | Cod sursa (job #951524) | Cod sursa (job #1006981) | Cod sursa (job #1009083) | Cod sursa (job #2509106)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <ctime>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMax = 50005;
const int oo = (1 << 30); // max int
int N, M;
int D[NMax]; // distance
bool Inqueue[NMax]; // inqueue[i] = true if node is visited
vector < pair < int, int > > G[NMax];
struct compdist {
bool operator()(int x, int y) {
return D[x] > D[y];
}
};
priority_queue < int, vector < int >, compdist> Queue;
// push nodes ascending regarding the cost
void Read() {
fin >> N >> M;
for(int i = 1; i <= M; i++) {
int x, y, c;
fin >> x >> y >> c;
G[x].push_back(make_pair(y,c));
}
}
void Dijkstra(int s) {
for(int i = 1; i <= N; i++) {
D[i] = oo;
Inqueue[i] = false;
}
D[s] = 0;
Queue.push(s);
Inqueue[s] = true;
while(!Queue.empty()) {
int nodCurrent = Queue.top(); // take node with smallest cost
for(unsigned int i = 0; i < G[nodCurrent].size(); i++) {
int Neighbour = G[nodCurrent][i].first;
int Cost = G[nodCurrent][i].second;
if(D[nodCurrent] + Cost < D[Neighbour]) {
D[Neighbour] = D[nodCurrent] + Cost;
if(Inqueue[Neighbour] == false) {
Queue.push(Neighbour);
Inqueue[Neighbour] = true;
}
}
}
Inqueue[nodCurrent] = false;
Queue.pop();
}
}
void Write() {
for(int i = 2; i <= N; i++) {
if(D[i] != oo)
fout << D[i] << " ";
else
fout << "0 "; // if there is no path to the node
}
}
int main()
{
Read();
double start = clock();
Dijkstra(1);
double end = clock();
double rez = (end - start) / CLOCKS_PER_SEC;
cout << rez;
Write();
return 0;
}