Pagini recente » Cod sursa (job #3122084) | Cod sursa (job #1954165) | Cod sursa (job #1578249) | Cod sursa (job #1649342) | Cod sursa (job #2982883)
#include <fstream>
#include <vector>
#include <queue>
#define DIM 50005
#define INF 0x3f3f3f3f
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
struct elem {
int node, cost;
bool operator < (elem x) const {
return cost < x.cost;
}
};
int n, m, dist[DIM];
vector<pair<int, int>> edges[DIM];
priority_queue<elem> pq;
void dijkstra(int node) {
pq.push({node, 0});
while (!pq.empty()) {
int node = pq.top().node;
int cost = pq.top().cost;
pq.pop();
if (cost > dist[node])
continue;
for (auto child: edges[node]) {
if (dist[child.first] > cost + child.second) {
dist[child.first] = cost + child.second;
pq.push({child.first, dist[child.first]});
}
}
}
}
int main() {
f >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
f >> x >> y >> c;
edges[x].push_back({y, c});
}
for (int i = 1; i <= n; i++) {
dist[i] = INF;
}
dijkstra(1);
for (int i = 2; i <= n; i++) {
if (dist[i] == INF) {
g << 0 << " ";
} else {
g << dist[i] << " ";
}
}
return 0;
}