Pagini recente » Cod sursa (job #2228513) | Cod sursa (job #3003384) | Cod sursa (job #2845058) | Cod sursa (job #2852069) | Cod sursa (job #2949979)
#include <fstream>
#include <vector>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n,x,y,z,t,cost,viz[50001],dist[50001],k,h[50001],m;
int oo=99999999;
vector<pair<int, int>>a[50001];
void erase_heap()
{
swap(h[1],h[k]);
swap(viz[h[1]],viz[h[k]]);
k--;
int tt=1,cc=2,ok=1;
while(ok&&cc<=k)
{
ok=0;
if(cc+1<=k&&dist[h[cc]]>dist[h[cc+1]])
cc++;
if(dist[h[cc]]<dist[h[tt]])
{
swap(h[cc],h[tt]);
swap(viz[h[cc]],viz[h[tt]]);
ok=1;
}
tt=cc;
cc*=2;
}
}
void update(int poz)
{
while(poz>1&&dist[h[poz]]<dist[h[poz/2]])
{
swap(h[poz/2],h[poz]);
swap(viz[h[poz/2]],viz[h[poz]]);
poz/=2;
}
}
void add_heap(int ind,int val)
{
h[++k]=ind;
dist[ind]=val;
viz[ind]=k;
update(k);
}
void dijkstra()
{
viz[1]=1;
dist[1]=0;
h[1]=1;
k=1;
while(k)
{
t=h[1];
cost=dist[t];
erase_heap();
for(int i=0;i<a[t].size();i++)
{
x=a[t][i].first;
y=a[t][i].second;
if(dist[x]>cost+y)
{
if(dist[x]==oo)
{
add_heap(x,cost+y);
}
else
{
dist[x]=cost+y;
update(viz[x]);
}
}
}
}
}
int main()
{
f>>n>>m;
for(int i=1;i<=m;i++)
{
f>>x>>y>>z;
a[x].push_back(make_pair(y,z));
}
for(int i=1;i<=n;i++)
{
dist[i]=oo;
viz[i]=-1;
}
dijkstra();
for(int i=2;i<=n;i++)
if(dist[i]==oo)
g<<0<<" ";
else
g<<dist[i]<<" ";
return 0;
}