Pagini recente » Cod sursa (job #1717574) | Cod sursa (job #90369) | Cod sursa (job #802581) | Cod sursa (job #1453453) | Cod sursa (job #2850557)
#include <fstream>
#include <climits>
#include <vector>
#include <queue>
#define NMAX 50005
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
typedef pair<int, int> pi;
int n, m, x, y, cost;
int dp[NMAX];
vector <pi> neighbours[NMAX];
priority_queue <pi, vector <pi>, greater<pi> > q;
void dijkstra(int start) {
dp[start] = 0;
q.push({0, start});
while (!q.empty()) {
int cost = q.top().first;
int node = q.top().second;
q.pop();
if (dp[node] == cost) {
for (auto neighbour : neighbours[node]) {
int newNode = neighbour.first;
int newCost = neighbour.second;
if (cost + newCost < dp[newNode]) {
dp[newNode] = cost + newCost;
q.push({dp[newNode], newNode});
}
}
}
}
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++) {
f >> x >> y >> cost;
neighbours[x].push_back({y, cost});
}
for (int i = 1; i <= n; i++)
dp[i] = INT_MAX;
dijkstra(1);
for (int i = 2; i <= n; i++) {
if (dp[i] == INT_MAX)
g << "0 ";
else
g << dp[i] << " ";
}
g << "\n";
return 0;
}