Pagini recente » Cod sursa (job #49093) | Cod sursa (job #651437) | Cod sursa (job #901531) | Rating Costel Puicula (mazgozaur) | Cod sursa (job #1857486)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int kInfinite = (1 << 30);
struct Node
{
int distance;
vector<pair<int, int>> edges;
Node()
{
distance = kInfinite;
}
};
typedef vector<Node> Graph;
typedef pair<int, int> Pair;
void Dijkstra(Graph &g, int start)
{
auto cmp = [](const Pair &a, const Pair &b) -> bool {
return a.first > b.first;
};
priority_queue<Pair, vector<Pair>, decltype(cmp)> q(cmp);
g[start].distance = 0;
q.push({0, 0});
vector<bool> visited(g.size(), false);
while (!q.empty()) {
int node = q.top().second;
q.pop();
if (visited[node]) {
continue;
}
visited[node] = true;
for (const auto &edge : g[node].edges) {
int new_cost = g[node].distance + edge.second;
if (new_cost < g[edge.first].distance) {
g[edge.first].distance = new_cost;
q.push({new_cost, edge.first});
}
}
}
}
int main()
{
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
fin >> n >> m;
Graph graph(n);
while (m--) {
int x, y, c;
fin >> x >> y >> c;
graph[x - 1].edges.push_back({y - 1, c});
graph[y - 1].edges.push_back({x - 1, c});
}
Dijkstra(graph, 0);
for (int i = 1; i < n; ++i) {
fout << graph[i].distance << " ";
}
return 0;
}