Pagini recente » Cod sursa (job #3229311) | Cod sursa (job #2900791) | Cod sursa (job #429150) | Cod sursa (job #1873526) | Cod sursa (job #1996416)
#include <fstream>
#include <vector>
#define MAXN 60002
#define Inf 20000002
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct two{
int nod, c;
};
vector <two> G[MAXN];
int heap[MAXN];
int d[MAXN], viz[MAXN];
int nn, n, m, x, y, z, left_son, right_son, father, fiu, cost;
inline void urca(int tata, int fiu)
{
while (d[heap[tata]] > d[heap[fiu]] && tata > 0)
{
swap(heap[tata], heap[fiu]);
fiu = tata; tata /= 2;
}
}
inline void Adauga_heap(int ndd)
{
heap[++nn] = ndd;
urca(nn/2, n);
}
inline void coboara(int ndd)
{
father = ndd;
for (; ;)
{
left_son = father * 2; right_son = father * 2 + 1;
if (left_son <= nn)
{
if (right_son <= nn)
{
if (d[heap[left_son]] < d[heap[right_son]])
{
if (d[heap[father]] > d[heap[left_son]])
{
swap(heap[father], heap[left_son]);
father = left_son;
continue;
}
else
break;
}
else
{
if (d[heap[father]] > d[heap[right_son]])
{
swap(heap[father], heap[right_son]);
father = right_son;
continue;
}
else
break;
}
}
else
{
if (d[heap[father]] > d[heap[left_son]])
{
swap(heap[father], heap[left_son]);
father = left_son;
continue;
}
else
break;
}
}
else
break;
}
}
inline void Elimina_heap()
{
heap[1] = heap[nn];
nn--;
coboara(1);
}
inline void Read()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> z;
G[x].push_back({y, z});
G[y].push_back({x, z});
}
}
inline void Initializer()
{
Adauga_heap(1);
for (int i = 2; i <= n; i++)
d[i] = Inf;
}
inline void Dijkstra()
{
while (nn)
{
fiu = heap[1];
viz[fiu] = 1;
Elimina_heap();
for (vector <two> :: iterator i = G[fiu].begin(); i != G[fiu].end(); i++)
{
if (d[fiu] + (*i).c < d[(*i).nod])
{
d[(*i).nod] = d[fiu] + (*i).c;
Adauga_heap((*i).nod);
}
}
}
}
inline void Write()
{
for (int i = 2; i <= n; i++)
{
if (d[i] == Inf)
d[i] = 0;
fout << d[i] << " ";
}
}
int main ()
{
Read();
Initializer();
Dijkstra();
Write();
fin.close(); fout.close(); return 0;
}