Pagini recente » Cod sursa (job #108100) | Cod sursa (job #1106459) | Cod sursa (job #812275) | Cod sursa (job #360729) | Cod sursa (job #2870884)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const string filename = "dijkstra";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
const int inf = 0x3f3f3f3f;
int n, m, dist[50005];
bool used[50005];
struct heapNode {
int nod, cost;
bool operator < (const heapNode &other) const
{
return cost > other.cost;
}
};
vector <heapNode> G[50005];
priority_queue <heapNode> heap;
void dijkstra(int sursa)
{
for(int i = 1; i <= n; i++)
dist[i] = inf;
heap.push({sursa, 0});
dist[sursa] = 0;
while(!heap.empty())
{
heapNode nod = heap.top();
heap.pop();
if(used[nod.nod])
continue;
used[nod.nod] = 1;
for(heapNode vecin : G[nod.nod])
{
if(dist[nod.nod] + vecin.cost < dist[vecin.nod])
{
dist[vecin.nod] = dist[nod.nod] + vecin.cost;
heap.push({vecin.nod, dist[vecin.nod]});
}
}
}
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
int a, b, c;
fin >> a >> b >> c;
G[a].push_back({b, c});
}
dijkstra(1);
for(int i = 2; i <= n; i++)
{
if(dist[i] == inf)
dist[i] = 0;
fout << dist[i] << ' ';
}
return 0;
}