Pagini recente » Cod sursa (job #1070208) | Monitorul de evaluare | Cod sursa (job #1662130) | Cod sursa (job #1634551) | Cod sursa (job #2374850)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 50001;
const int inf = 1 << 30;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int d[maxn], viz[maxn];
int n,m;
struct Nod
{
int y,cost;
Nod()
{
y=0;
cost=0;
}
inline Nod(int _y, int _cost)
{
y=_y;
cost=_cost;
}
inline bool operator < (const Nod &x) const
{
return cost>x.cost;
}
};
vector <Nod> v[maxn];
priority_queue <Nod>c;
void citire()
{
f>>n>>m;
int x, y, cost;
for ( int i = 1; i <= m; ++i )
{
f>>x>>y>>cost;
v[x].push_back(Nod(y, cost));
}
}
void dijkstra_heap(int x)
{
for ( int i = 1; i <= n; ++i )
{
d[i] = inf;
viz[i] = 0;
}
d[x] = 0;
int nod, next;
c.push(Nod(1, 0));
while (!c.empty())
{
nod = c.top().y;
c.pop();
if (viz[nod] == 0)
{
viz[nod] = 1;
for (vector <Nod>::iterator it = v[nod].begin(); it != v[nod].end(); ++it)
{
next = it->y;
if (d[next] > d[nod] + it->cost)
{
d[next] = d[nod] + it->cost;
c.push(Nod(next, d[next]));
}
}
}
}
}
int main()
{
citire();
dijkstra_heap(1);
for ( int i = 2; i <= n; ++i )
if (d[i]==inf) g << 0 << " ";
else g<<d[i]<<" ";
}