Pagini recente » Cod sursa (job #2354501) | Cod sursa (job #1629104) | Cod sursa (job #411755) | Cod sursa (job #212030) | Cod sursa (job #2543735)
#include<fstream>
#include<iostream>
#include<vector>
#include<queue>
#define oo 1000000000
#define MAX_V 50000
using namespace std;
vector<pair<int, int>>g[MAX_V + 1];
int dist[MAX_V + 1], n, m;
class ComparVf {
public:
bool operator() (const int& x, const int& y) {
return dist[x] > dist[y];
}
};
priority_queue<int, vector<int>, ComparVf> H;
void readGraph() {
int x, y, c;
ifstream fin("dijkstra.in");
fin >> n >> m;
for(int i = 1; i <= m; i++) {
fin >> x >> y >> c;
g[x].push_back(make_pair(y, c));
}
fin.close();
}
void Dijkstra(int source) {
int i, vfmin;
for(i = 1; i <= n; i++) {
dist[i] = oo;
}
dist[source] = 0;
H.push(source);
while(!H.empty()) {
vfmin = H.top();
H.pop();
for(auto j : g[vfmin]) {
if(dist[j.first] > dist[vfmin] + j.second) {
dist[j.first] = dist[vfmin] + j.second;
H.push(j.first);
}
}
}
}
void printDistances() {
ofstream fout("dijkstra.out");
for(int i = 2; i <= n; i++)
if(dist[i] == oo)
fout << "0 ";
else fout << dist[i] << " ";
fout << "\n";
fout.close();
}
int main() {
readGraph();
Dijkstra(1);
printDistances();
return 0;
}