Pagini recente » Cod sursa (job #1235784) | Cod sursa (job #989219) | Cod sursa (job #1628984) | Cod sursa (job #1448348) | Cod sursa (job #1996406)
#include <fstream>
#include <vector>
#define MAXN 50002
#define Inf 1000002
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct two{
int nod, c;
};
vector <two> G[MAXN];
two 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 (heap[tata].c > heap[fiu].c && tata > 0)
{
swap(heap[tata], heap[fiu]);
fiu = tata; tata /= 2;
}
}
inline void Adauga_heap(int nod, int cost)
{
heap[++nn] = {nod, cost};
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 (heap[left_son].c < heap[left_son].c)
{
if (heap[father].c > heap[left_son].c)
{
swap(heap[father], heap[left_son]);
father = left_son;
continue;
}
else
break;
}
else
{
if (heap[father].c > heap[right_son].c)
{
swap(heap[father], heap[right_son]);
father = right_son;
}
else
break;
}
}
else
{
if (heap[father].c > heap[left_son].c)
{
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 Dijkstra()
{
while (nn)
{
fiu = heap[1].nod;
cost = heap[1].c;
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, (*i).c);
}
}
}
}
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, 0);
for (int i = 2; i <= n; i++)
d[i] = Inf;
}
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;
}