Pagini recente » Cod sursa (job #108795) | Cod sursa (job #1646934) | Cod sursa (job #2194379) | Cod sursa (job #2166815) | Cod sursa (job #3206379)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const string filename = "dijkstra";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
const int maxN = 50005, inf = 0x3f3f3f3f;
int n, m, dist[maxN];
bool used[maxN];
struct heapNode {
int nod, cost;
bool operator < (const heapNode &other) const
{
return cost > other.cost;
}
};
vector <heapNode> G[maxN];
priority_queue <heapNode> heap;
void dijkstra(int start)
{
for(int i = 1; i <= n; i++)
dist[i] = inf;
dist[start] = 0;
heap.push({start, 0});
while(!heap.empty())
{
heapNode curr = heap.top();
heap.pop();
if(used[curr.nod])
continue;
used[curr.nod] = 1;
for(heapNode nxt : G[curr.nod])
{
if(dist[curr.nod] + nxt.cost < dist[nxt.nod])
{
dist[nxt.nod] = dist[curr.nod] + nxt.cost;
heap.push({nxt.nod, dist[nxt.nod]});
}
}
}
}
int main()
{
fin >> n >> m;
for(int x, y, c, i = 1; i <= m; i++)
{
fin >> x >> y >> c;
G[x].push_back({y, c});
}
dijkstra(1);
for(int i = 2; i <= n; i++)
{
if(dist[i] == inf)
dist[i] = 0;
fout << dist[i] << ' ';
}
return 0;
}