Pagini recente » Cod sursa (job #3163166) | Cod sursa (job #1595816) | Cod sursa (job #2034819) | Cod sursa (job #2764315) | Cod sursa (job #2844146)
#include <fstream>
#include <vector>
#define N 50001
#define M 250001
#define INF 1000000001
using namespace std;
ifstream in ("dijkstra.in");
ofstream out ("dijkstra.out");
vector<pair<int,int>> succ[N];
int lst[N], d[N], h[N], pos[N], n, m, nr, nh;
void swap(int p1, int p2)
{
int aux = h[p1];
h[p1] = h[p2];
h[p2] = aux;
pos[h[p1]] = p1;
pos[h[p2]] = p2;
}
void add_edge(int x, int y, int c)
{
pair<int,int> e;
e.first=y;
e.second=c;
succ[x].push_back(e);
}
void up(int p)
{
while (p > 1 && d[h[p]] < d[h[p/2]])
{
swap(p, p/2);
p /= 2;
}
}
void down(int p)
{
int lc = 2*p, rc = 2*p + 1, next = p;
if (lc <= nh && d[h[lc]] < d[h[next]])
{
next = lc;
}
if (rc <= nh && d[h[rc]] < d[h[next]])
{
next = rc;
}
if (next != p)
{
swap(next,p);
down(next);
}
}
void remove(int p)
{
if (p == nh)
{
nh--;
}
else
{
h[p] = h[nh--];
pos[h[p]] = p;
down(p);
}
}
void dijkstra(int x0)
{
for (int i = 1; i <= n; i++)
{
d[i] = INF;
}
d[x0] = 0;
h[++nh] = x0;
pos[x0] = nh;
while (nh > 0)
{
int x = h[1];
remove(1);
for (auto p: succ[x])
{
int y = p.first;
int c = p.second;
if (d[x] + c < d[y])
{
d[y] = d[x] + c;
if (pos[y] == 0)
{
h[++nh] = y;
pos[y] = nh;
}
up(pos[y]);
}
}
}
}
int main()
{
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
add_edge(x, y, c);
}
dijkstra(1);
for (int i = 2; i <= n; i++)
{
if (d[i] == INF)
{
d[i] = 0;
}
out << d[i] << " ";
}
return 0;
}