Pagini recente » Cod sursa (job #1535237) | Cod sursa (job #2236692) | Cod sursa (job #1803189) | Cod sursa (job #2792718) | Cod sursa (job #2198412)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
#define MAXN 50001
class Edge {
public:
int node;
int cost;
Edge(int node, int cost) {
this->node = node;
this->cost = cost;
}
};
class Compare {
public:
bool operator() (Edge a, Edge b) {
return a.cost < b.cost;
}
};
int n, m;
vector<vector<Edge>> adj(MAXN);
vector<long> distances;
void read() {
fstream fin("dijkstra.in", ios::in);
fin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y, c;
fin >> x >> y >> c;
adj[x].push_back(Edge(y, c));
}
fin.close();
}
void dijsktra(int source) {
priority_queue<Edge, vector<Edge>, Compare> heap;
for (int i = 0; i <= n; i++) {
distances.push_back(1 << 30);
}
distances[source] = 0;
heap.push(Edge(source, 0));
while (!heap.empty()) {
int node = heap.top().node;
heap.pop();
for (Edge neighbour : adj[node]) {
if (distances[neighbour.node] > distances[node] + neighbour.cost) {
distances[neighbour.node] = distances[node] + neighbour.cost;
heap.push(neighbour);
}
}
}
}
void write() {
fstream fout("dijkstra.out", ios::out);
for (int i = 1; i <= n; i++) {
fout << distances[i] << " ";
}
fout.close();
}
int main() {
read();
dijsktra(1);
write();
return 0;
}