Cod sursa(job #556366)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 16 martie 2011 09:13:34
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include<cstdio>
#define Nmx 50001
#define INF 20000001

using namespace std;

int n,m,dist[Nmx],viz[Nmx];
int coada[Nmx*10];
struct nod
{
	int inf,cost;
	nod *urm;
};
nod *G[Nmx];

void add(int x,int y,int c)
{
	nod *aux=new nod;
	aux->inf = y;
	aux->cost = c;
	aux->urm = G[x];
	G[x]=aux;
}

void citire()
{
	int x,y,c;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;++i)
	{
		scanf("%d%d%d",&x,&y,&c);
		add(x,y,c);
	}
}

void solve()
{
	for(int i=2;i<=n;++i)
		dist[i]=INF;
	dist[1]=0;
	int st,dr;
	st=dr=1;
	coada[1]=1;
	viz[1]=1;
	while(st<=dr)
	{
		int x=coada[st];
		viz[x]=0;
		for(nod *p=G[x];p;p=p->urm)
			if(p->cost+dist[x]<dist[p->inf])
			{
				dist[p->inf]=p->cost+dist[x];
				if(viz[p->inf]==0)
				{
					viz[p->inf]=1;
					coada[++dr]=p->inf;
				}
			}
		++st;
	}
	for(int i=2;i<=n;++i)
		if(dist[i]==INF)
			printf("0 ");
		else printf("%d ",dist[i]);
}

int main()
{
	freopen("dijkstra.in","r",stdin);
	freopen("dijkstra.out","w",stdout);
	citire();
	solve();
	printf("\n");
	return 0;
}