Pagini recente » Cod sursa (job #2963505) | Borderou de evaluare (job #2378412) | Cod sursa (job #1149926) | Borderou de evaluare (job #2149654) | Cod sursa (job #1967128)
#include <fstream>
#include <vector>
#include <climits>
#define MAXN 50004
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct punct{
int c, graf;
};
vector <punct> G[MAXN];
punct heap[MAXN];
int n, m, cost[MAXN], fr[MAXN], nn, viz[MAXN];
inline void Read()
{
int x, y, z;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> z;
G[x].push_back({z, y});
}
}
inline void up(int son)
{
int father;
while (son >= 1)
{
father = son / 2;
if (heap[father].c > heap[son].c)
{
fr[heap[father].graf] = son;
fr[heap[son].graf] = father;
swap(heap[father], heap[son]);
son = father;
}
else
return;
}
}
inline void down(int father)
{
int left_son = father * 2;
int right_son = father * 2 + 1;
while (father <= nn)
{
left_son = father * 2;
right_son = father * 2 + 1;
if (right_son <= nn)
{
if (heap[left_son].c < heap[right_son].c && heap[father].c > heap[left_son].c)
{
fr[heap[father].graf] = left_son;
fr[heap[left_son].graf] = father;
swap(heap[left_son], heap[father]);
father = left_son;
}
else if (heap[right_son].c < heap[father].c && heap[left_son].c > heap[right_son].c)
{
fr[heap[father].graf] = right_son;
fr[heap[right_son].graf] = father;
swap(heap[right_son], heap[father]);
father = right_son;
}
else
return;
}
else if (left_son <= nn)
{
if (heap[father].c > heap[left_son].c)
{
fr[heap[father].graf] = left_son;
fr[heap[left_son].graf] = father;
swap(heap[left_son], heap[father]);
father = left_son;
}
else
return;
}
else
return;
}
}
inline void Solve()
{
for (int i = 1; i <= n; i++)
{
cost[i] = INT_MAX;
}
heap[1] = {0, 1};
cost[1] = 0;
nn = 1;
int gr;
while (nn > 0)
{
gr = heap[1].graf;
for (vector <punct> :: iterator i = G[gr].begin(); i != G[gr].end(); i++)
{
if (viz[(*i).graf] == 0)
{
if (cost[gr] + (*i).c < cost[(*i).graf])
{
cost[(*i).graf] = cost[gr] + (*i).c;
if (fr[(*i).graf] != 0)
{
heap[fr[(*i).graf]].c = cost[(*i).graf];
up(fr[(*i).graf]);
}
else
{
heap[++nn].c = cost[(*i).graf];
heap[nn].graf = (*i).graf;
fr[heap[nn].graf] = nn;
up(nn);
}
}
}
}
viz[gr] = 1;
heap[1] = heap[nn];
fr[heap[1].graf] = 1;
nn--;
down(1);
}
}
inline void Afisare()
{
for (int i = 2; i <= n; i++)
{
if (cost[i] == INT_MAX)
{
cost[i] = 0;
}
fout << cost[i] << " ";
}
}
int main ()
{
Read();
Solve();
Afisare();
fin.close(); fout.close(); return 0;
}