Pagini recente » Cod sursa (job #1262258) | Cod sursa (job #1637876) | Cod sursa (job #377175) | Cod sursa (job #1284568) | Cod sursa (job #2865736)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const long long infinity = 2e12;
struct Edge
{
int destination;
int cost;
inline bool operator < (const Edge& other) const
{
return cost > other.cost;
}
};
int n, m;
vector <Edge> graph[50005];
priority_queue <Edge> heap;
long long distances[50005];
bool visited[50005];
void Dijkstra(int start)
{
for (int i = 1; i <= n; i++)
{
distances[i] = infinity;
}
distances[1] = 0;
Edge startingEdge = {start, 0};
heap.push(startingEdge);
while (!heap.empty())
{
Edge currEdge = heap.top();
heap.pop();
if (visited[currEdge.destination])
{
continue;
}
visited[currEdge.destination] = true;
for (Edge edge : graph[currEdge.destination])
{
if (distances[edge.destination] <= edge.cost + distances[currEdge.destination])
{
continue;
}
distances[edge.destination] = edge.cost + distances[currEdge.destination];
edge.cost = distances[edge.destination];
heap.push(edge);
}
}
}
int main()
{
ios::sync_with_stdio(false);
fin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b, c;
fin >> a >> b >> c;
Edge newEdge = {b, c};
graph[a].push_back(newEdge);
}
Dijkstra(1);
for (int i = 2; i <= n; i++)
{
if (distances[i] == infinity)
{
fout << 0 << ' ';
}
else
{
fout << distances[i] << ' ';
}
}
fout << '\n';
}