Pagini recente » Cod sursa (job #411619) | Cod sursa (job #1653918) | Cod sursa (job #1459482) | Cod sursa (job #1115875) | Cod sursa (job #1826333)
#include <bits/stdc++.h>
using namespace std;
struct Edge
{
int target, weight;
};
struct Node
{
vector<Edge> adj;
int dist;
Node() { dist = INT_MAX; }
};
struct Order
{
bool operator()(const pair<int, int>& a, const pair<int, int>& b)
{
return a.first < b.first;
}
};
int N, M;
Node V[50005];
void dijkstra(int source)
{
V[source].dist = 0;
priority_queue<pair<int, int>, vector<pair<int, int> >, Order> heap;
heap.push({source, 0});
while (!heap.empty())
{
pair<int, int> current = heap.top();
heap.pop();
if (V[current.first].dist < current.second) continue;
for (auto edge : V[current.first].adj)
{
int newDist = V[current.first].dist + edge.weight;
if (V[edge.target].dist > newDist)
{
V[edge.target].dist = newDist;
heap.push({edge.target, newDist});
}
}
}
}
int main()
{
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
int x, y, w;
scanf("%d %d %d", &x, &y, &w);
Edge e;
e.target = y;
e.weight = w;
V[x].adj.push_back(e);
}
dijkstra(1);
for (int i = 2; i <= N; i++)
{
printf("%d ", V[i].dist);
}
printf("\n");
}