Pagini recente » Cod sursa (job #1201817) | Cod sursa (job #2866561) | Cod sursa (job #1524430) | Cod sursa (job #99532) | Cod sursa (job #3125906)
#include <fstream>
#include <vector>
using namespace std;
const int N = 5e4;
const int INF = 1 << 30;
struct succesor
{
int vf, c;
};
vector <succesor> s[N+1];
bool selectat[N+1];
int n, nh, d[N+1], h[N+1], poz[N+1];
void schimb(int p1, int p2)
{
swap(p1, 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 x)
{
h[++nh] = x;
poz[x] = nh;
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_1()
{
h[1] = h[nh--];
poz[h[1]] = 1;
coboara(1);
}
void dijkstra(int x0)
{
for (int i = 1; i <= n; i++)
{
d[i] = INF;
selectat[i] = false;
}
d[x0] = 0;
adauga(x0);
while (nh > 0)
{
int x = h[1];
sterge_1();
selectat[x] = true;
for (auto p: s[x])
{
int y = p.vf;
int c = p.c;
if (selectat[y])
{
continue;
}
if (d[x] + c < d[y])
{
d[y] = d[x] + c;
if (poz[y] != 0)
{
urca(poz[y]);
}
else
{
adauga(y);
}
}
}
}
}
int main()
{
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
s[x].push_back((succesor){y, c});
}
dijkstra(1);
for (int i = 2; i <= n; i++)
{
if (d[i] == INF)
{
d[i] = 0;
}
out << d[i] << " ";
}
in.close();
out.close();
return 0;
}