Pagini recente » Cod sursa (job #1179782) | Cod sursa (job #903278) | Cod sursa (job #2139141) | Cod sursa (job #550960) | Cod sursa (job #1201221)
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#define NMAX 50001
using namespace std;
struct graf
{
int l,r;
};
vector<graf>v[NMAX];
int H[NMAX*2+1],Poz[NMAX],cost[NMAX];
int lg,i,n,m,x,y,c;
void pop(int poz)
{
while (poz>1 && cost[H[poz]]<cost[H[poz/2]])
{
swap(H[poz],H[poz/2]);
swap(Poz[H[poz]],Poz[H[poz/2]]);
poz=poz/2;
}
}
void bagaheap(int nod)
{
H[++lg]=nod;
Poz[nod]=lg;
pop(lg);
}
void push(int poz)
{
while ((poz*2<=lg && cost[H[poz]]>cost[H[poz*2]]) || (poz*2+1<=lg && cost[H[poz]]>cost[H[poz*2+1]]))
{
if (cost[H[poz*2]]<cost[H[poz*2+1]] || poz*2+1>lg)
{
swap(H[poz*2],H[poz]);
swap(Poz[H[poz*2]],Poz[H[poz]]);
poz*=2;
}
else
{
swap(H[poz*2+1],H[poz]);
swap(Poz[H[poz*2+1]],Poz[H[poz]]);
poz=poz*2+1;
}
}
}
int Minim()
{
int Min=H[1];
swap(H[1],H[lg]);
swap(Poz[1],Poz[lg]);
--lg;
push(1);
Poz[Min]=0;
return Min;
}
int main()
{
freopen("dijkstra.in","r",stdin);
freopen("dijkstra.out","w",stdout);
scanf("%d%d",&n,&m);
for (i=1;i<=m;++i)
{
scanf("%d%d%d",&x,&y,&c);
graf X;
X.l=x,X.r=c;
v[y].push_back(X);
X.l=y;
v[x].push_back(X);
}
bagaheap(1);cost[1]=0;Poz[1]=1;
for (i=2;i<=n;++i)
{
Poz[i]=0;
cost[i]=INFINITY;
}
int val=INFINITY;
for (i=1;i<=n;++i)
{
int u=Minim();
vector<graf>::iterator it;
for (it=v[u].begin();it!=v[u].end();++it)
{
graf vf=*it;
if (cost[vf.l]>vf.r+cost[u])
{
cost[vf.l]=vf.r+cost[u];
if (Poz[vf.l]!=0) pop(Poz[vf.l]);
else bagaheap(vf.l);
}
}
}
for (i=2;i<=n;++i)
if (cost[i]!=val) printf("%d ",cost[i]);
else printf("%d ",0);
printf("\n");
return 0;
}