Pagini recente » Cod sursa (job #2745299) | Cod sursa (job #529762) | Cod sursa (job #1357418) | Cod sursa (job #438773) | Cod sursa (job #520781)
Cod sursa(job #520781)
#include <stdio.h>
#include <queue>
#define NMAX 50001
# define INF 0x3f3f3f3f
using namespace std;
struct nod{
int inf,cost;
nod *urm;
};
nod *g[NMAX];
int n,m;
struct vec{
int dist,pred;
};
vec v[NMAX];
queue < int > Q;
void add(int x,int y,int z)
{
nod *aux=new nod;
aux->inf=y;
aux->cost=z;
aux->urm=g[x];
g[x]=aux;
}
void citire()
{
freopen ("dijkstra.in","r",stdin);
scanf ("%d%d",&n,&m);
int x,y,z;
for (int i=1;i<=m;i++)
{
scanf ("%d%d%d",&x,&y,&z);
add(x,y,z);
}
v[1].dist=0;
v[1].pred=0;
for (int i=2;i<=n;i++)
v[i].dist=INF,v[i].pred=0;
Q.push(1);
int viz[NMAX];
viz[1]=1;
while (!Q.empty())
{
int nd=Q.front();
Q.pop();
viz[nd]=0;
for (nod *p=g[nd];p;p=p->urm)
{
int u=nd;
int t=p->inf;
if (v[u].dist+p->cost<v[t].dist)
{
v[t].dist=v[u].dist+p->cost;
v[t].pred=u;
if (!viz[t])
{
Q.push(t);
viz[t]=1;
}
}
}
}
}
void afis()
{
freopen ("dijkstra.out","w",stdout);
for (int i=2;i<=n;i++)
{
if (v[i].dist<INF)
printf("%d ",v[i].dist);
else
printf("0 ");
}
}
int main()
{
citire();
afis();
return 0;
}