Pagini recente » Cod sursa (job #1035295) | Cod sursa (job #1351825) | Cod sursa (job #2665844) | Cod sursa (job #1705749) | Cod sursa (job #1246504)
#include <iostream>
#include <fstream>
#include <map>
#include <queue>
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
typedef pair<int, int> P;
// Reutrn distance from node 1 to each of other nodes.
void Dijkstra(map<int, vector<pair<int, int>>> &graph,
const int& n, vector<int>* result) {
result->clear();
result->resize(n + 1);
priority_queue<P, vector<P>, greater<P>> heap;
heap.push(make_pair(0, 1));
map<int, bool> visited;
map<int, int> candidate;
while (!heap.empty()) {
const auto p = heap.top();
heap.pop();
const int& cost = p.first;
const int& node = p.second;
if (visited[node]) {
continue;
}
visited[node] = true;
(*result)[node] = cost;
for (const auto& edge : graph[node]) {
const int& neighbour = edge.first;
const int& edge_cost = edge.second;
if (visited[neighbour] ||
((candidate[neighbour] > 0)
&& (candidate[neighbour] > cost + edge_cost))) {
continue;
}
candidate[neighbour] = cost + edge_cost;
heap.push(make_pair(cost + edge_cost, neighbour));
}
}
}
int main (int argc, char const *argv[]) {
int n, m;
in>>n>>m;
map<int, vector<P>> graph;
for (int i = 0; i < m; ++i) {
int x, y, c;
in>>x>>y>>c;
graph[x].push_back(make_pair(y, c));
}
vector<int> result;
Dijkstra(graph, n, &result);
for (int i = 2; i <= n; ++i) {
out<<result[i]<< " ";
}
return 0;
}