Pagini recente » Cod sursa (job #1617853) | Cod sursa (job #135725) | Cod sursa (job #2858157) | Cod sursa (job #2732068) | Cod sursa (job #553576)
Cod sursa(job #553576)
#include<fstream.h>
#include<vector>
#include<algorithm>
using namespace std;
struct dij { int ind,cost;};
vector < pair <int, int> > v[50005];
int m,n,p,poz[51000],h[50100],dist[50100],sw[50100];
void upheap (int k)
{
int h1,h2;
while (k>=1 && dist[h[k]]<dist[h[k>>=1]])
{
h1=h[k],h2=h[k>>1];
poz[h1]=(poz[h1]^poz[h2])^(poz[h2]=poz[h1]);
h[k]=(h[k>>=1]^h[k])^(h[k>>=1]=h[k]);
k>>=1;
}
}
void downheap()
{
int x=1,y=p,h1;
while (x!=y)
{
y=x;
h1=h[y];
if (y<<1<=p && dist[h1]>dist[h[x<<1]]) x<<=1;
if ((y<<1)+1<=p && dist[h1]>dist[h[(y<<1)+1]]) x=(y<<1)+1;
poz[h[x]]=(poz[h[x]]^poz[h1])^(poz[h1]=poz[h[x]]);
h[x]=(h[y]^h[x])^(h[y]=h[x]);
}
}
void dijkstra ()
{
vector< pair<int, int> >:: iterator it,it1,it2;
int inf,c,i;
inf=2000000000;
for (i=2;i<=n;i++)
dist[i]=inf;
dist[i]=0;
h[1]=1;
poz[1]=1;
sw[1]=1;
p=1;
while (p)
{
c=dist[h[1]];
it1=v[h[1]].begin();it2=v[h[1]].end();
for (it=it1;it<it2;++it)
if ((c+it->second)<dist[it->first])
if (sw[it->first]==1)
{
dist[it->first]=c+it->second;
upheap(poz[it->first]);
}
else
{
sw[it->first]=1;
dist[it->first]=c+it->second;
h[++p]=it->first;
upheap(p);
}
sw[h[1]]=0;
h[1]=h[p--];
poz[h[1]]=1;
downheap();
}
}
void afisare()
{
int i;
ofstream g("dijkstra.out");
int inf =2000000000;
for (i=2;i<=n;++i)
{
if (dist[i]==inf)
dist[i]=0;
g<<dist[i]<<' ';
}
g.close();
}
int main ()
{
int i,a,b,c;
dij nod;
ifstream f("dijkstra.in");
f>>n>>m;
for (i=1;i<=m;i++)
{
f>>a>>b>>c;
v[a].push_back(make_pair (b,c));
}
f.close();
dijkstra();
afisare();
return 0;
}