Pagini recente » Cod sursa (job #1119348) | Cod sursa (job #2086004) | Cod sursa (job #2877956) | Cod sursa (job #1157082) | Cod sursa (job #527543)
Cod sursa(job #527543)
#include<fstream>
#include<cstdio>
#include<vector>
#include<utility>
#define ff it->first
#define ss it->second
using namespace std;
int n,m,a,b,c,d[50005],oo=500000000,h[50010],poz[50010],i,l,nod,dist;
void read(),solve(),percolate(int t),sift(int f);
vector <pair<int,int> > v[50010];
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int main()
{
read();
solve();
return 0;
}
void read()
{
in>>n>>m;
for(;m;m--)
{
in>>a>>b>>c;
v[a].push_back(make_pair(b,c));
}
}
void solve()
{
vector<pair<int,int> >::iterator it;
for(i=1;i<=n;i++)
{
h[i]=i;
d[i]=oo;
poz[i]=i;
}
d[1]=0;
l=n;
for(;l;)
{
nod=h[1];
dist=d[nod];
for(it=v[nod].begin();it!=v[nod].end();it++)
if(d[ff]>dist+ss)
{
d[ff]=dist+ss;
percolate(poz[ff]);
}
h[1]=h[l];
poz[h[1]]=1;
l--;
sift(1);
}
for(i=2;i<=n;i++)
{
if(d[i]==oo)
d[i]=0;
out<<d[i]<<" ";
}
}
void percolate(int f)
{
int t,aux;
for(;;)
{
t=f>>1;
if(d[h[t]]<=d[h[f]])
return;
aux=h[t];
h[t]=h[f];
h[f]=aux;
poz[h[t]]=t;
poz[h[f]]=f;
f=t;
}
}
void sift(int t)
{
int f,aux;
for(;;)
{
f=t<<1;
if(f>l)
return;
if(f<l)
if(d[h[f]]<d[h[f+1]])
f++;
if(d[h[t]]<=d[h[f]])
return;
aux=h[t];
h[t]=h[f];
h[f]=aux;
poz[h[t]]=t;
poz[h[f]]=f;
t=f;
}
}