Pagini recente » Cod sursa (job #712605) | Cod sursa (job #2684742) | Cod sursa (job #3139628) | Cod sursa (job #1631981) | Cod sursa (job #3242242)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
struct edge {
int x;
int y;
int cost;
};
int n, m, x, y, cost;
vector<int> dijkstra(vector<vector<pair<int, int>>>& list, int start) {
struct compareFuncPairMin {
bool operator()(edge a, edge b) const {
return a.cost > b.cost;
}
};
priority_queue<edge, vector<edge>, compareFuncPairMin> heap;
vector<int> dist(n + 1, -1);
vector<int> parent(n + 1, 0);
dist[start] = 0;
for (auto& e : list[start]) {
heap.push({ start,e.first,e.second });
}
while (!heap.empty()) {
edge edge = heap.top();
heap.pop();
if (dist[edge.y] == -1 || dist[edge.x] + edge.cost < dist[edge.y]) {
dist[edge.y] = dist[edge.x] + edge.cost;
parent[edge.y] = edge.x;
for (auto& e : list[edge.y]) {
heap.push({ edge.y,e.first,e.second });
}
}
}
return dist;
}
int main()
{
cin >> n >> m;
vector<vector<pair<int, int>>> list(n+1);
for (int i = 0; i < m; i++) {
cin >> x >> y >> cost;
list[x].push_back({ y,cost });
list[y].push_back({ x,cost });
}
vector<int> dist = dijkstra(list, 1);
for (int i = 2; i < dist.size(); i++) {
cout << dist[i] << " ";
}
}