Pagini recente » Cod sursa (job #889148) | Cod sursa (job #1594931) | Cod sursa (job #2100239) | Cod sursa (job #851683) | Cod sursa (job #2906525)
#include <fstream>
#include <vector>
using namespace std;
const int N = 5e4;
const int INF = 1e9;
struct muchie
{
int y, c;
};
vector <muchie> a[N+1];
int h[N+1], d[N+1], poz[N+1], nh;
void schimb(int p1, int p2)
{
swap(h[p1], h[p2]);
poz[h[p1]] = p1;
poz[h[p2]] = p2;
}
void urca(int p)
{
while (p > 1 && d[h[p]] < d[h[p/2]])
{
schimb(p, p/2);
p /= 2;
}
}
void adauga(int vf)
{
h[++nh] = vf;
urca(nh);
}
void coboara(int p)
{
int fs = 2*p, fd = 2*p+1, bun = p;
if (fs <= nh && d[h[fs]] < d[h[bun]])
{
bun = fs;
}
if (fd <= nh && d[h[fd]] < d[h[bun]])
{
bun = fd;
}
if (bun != p)
{
schimb(bun, p);
coboara(bun);
}
}
void sterge(int p)
{
if (p == nh)
{
nh--;
}
else
{
schimb(p, nh--);
urca(p);
coboara(p);
}
}
int main()
{
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int n, m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
a[x].push_back((muchie){y, c});
}
in.close();
adauga(1);
for (int i = 2; i <= n; i++)
{
d[i] = INF;
}
while (nh != 0)///cat timp heap-ul nu e vid (mai am vf. accesibile din 1 neprelucrate)
{
int x = h[1];
sterge(1);
for (auto e: a[x])
{
int y = e.y, c = e.c;
if (d[x] + c < d[y])
{
d[y] = d[x] + c;
if (poz[y] != 0)///y este deja in heap (nu e primul drum pe care-l gasesc catre y)
{
urca(poz[y]);///dar e cel mai scurt
}
else
{
adauga(y);///y e unul dintre varfurile accesibile din 1 neprelucrate
}
}
}
}
for (int i = 2; i <= n; i++)
{
if (d[i] == INF)
{
d[i] = 0;
}
out << d[i] << " ";
}
out.close();
return 0;
}