Pagini recente » Cod sursa (job #161364) | Cod sursa (job #1910056) | Cod sursa (job #2258448) | Cod sursa (job #1978418) | Cod sursa (job #2758963)
#include <fstream>
#include <vector>
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int N = 5e4 + 1;
const int INF = 1e9 + 100;
int h[N],poz[N],nh,v[N],n,d[N],m;
vector <pair<int,int>> a[N];
void schimba(int p,int q)
{
swap(h[p],h[q]);
poz[h[p]] = p;
poz[h[q]] = q;
}
void urca(int p)
{
while(p > 1 && v[h[p]] < v[h[p/2]])
{
schimba(p,p/2);
p/=2;
}
}
void coboara(int p)
{
int fs = 2*p;
int fd = 2*p + 1;
int 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)
{
schimba(bun,p);
coboara(bun);
}
}
void stergere(int p)
{
if(p == nh)
{
nh--;
}
else
{
h[p] = h[nh--];
urca(p);
coboara(p);
}
}
void dijkstra(int x0)
{
for(int i = 2; i <= n; i++)
{
d[i] = INF;
h[nh++] = i;
poz[i] = nh;
}
d[x0] = 0;
urca(x0);
while(nh > 0)
{
int x = h[1];
stergere(1);
for(auto p:a[x])
{
int y = p.first;
int c = p.second;
if(d[y] > d[x] + c)
{
d[y] = d[x] + c;
urca(y);
}
}
}
}
int main()
{
in >> n >> m;
for(int i = 1; i <= n; i++)
{
int x,y,c;
in >> x >> y >> c;
a[x].push_back({y,c});
a[y].push_back({x,c});
}
in.close();
dijkstra(1);
for(int i = 2; i <= n; i++)
{
if(d[i] == INF)
{
d[i] = 0;
}
out << d[i] << " ";
}
out.close();
return 0;
}