Pagini recente » Cod sursa (job #1535355) | Cod sursa (job #2413295) | Cod sursa (job #423050) | Cod sursa (job #855818) | Cod sursa (job #3001366)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int NMAX = 50001;
const int INF = 2 * 1e9 + 1;
vector <pair <int, int> > a[NMAX];
int d[NMAX], h[NMAX], poz[NMAX];
void schimb(int p1, int p2)
{
swap(h[p1], h[p2]);
poz[h[p1]] = p1;
poz[h[p2]] = p2;
}
void urca(int h[], int p)
{
while(p > 1 && d[h[p]] < d[h[p / 2]])
{
schimb(p, p / 2);
p /= 2;
}
}
void adauga(int h[], int &nh, int x)
{
h[++nh] = x;
poz[x] = nh;
urca(h, nh);
}
void coboara(int h[], int nh, int p)
{
while (true)
{
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)
{
break;
}
schimb(p, bun);
p = bun;
}
}
void sterge(int h[], int &nh, int p)
{
if (p == nh)
nh--;
else
{
schimb(p, nh--);
urca(h, p);
coboara(h, nh, p);
}
}
void dijkstra(int x0)
{
d[x0] = 0;
int nh = 0;
adauga(h, nh, x0);
while(nh > 0)
{
int x = h[1];
sterge(h, nh, 1);
for(auto i: a[x])
{
int y = i.first;
int c = i.second;
if(d[y] > d[x] + c)
{
d[y] = d[x] + c;
if(poz[y] == 0)
adauga(h, nh, y);
else
urca(h, poz[y]);
}
}
}
}
int main()
{
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
fin >> n >> m;
for(int i = 1; i <= n; i++)
d[i] = INF;
for(int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
a[x].push_back(make_pair(y, c));
}
dijkstra(1);
for (int i = 2; i <= n; i++)
{
if (d[i] == INF)
fout << "0 ";
fout << d[i] << " ";
}
return 0;
}