Cod sursa(job #148709)

Utilizator the1dragonIonita Alexandru the1dragon Data 4 martie 2008 18:58:56
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<stdio.h>
#define N_MAX 1024*50
#define INFINIT 0x7FFFFFFF

struct entry
{
	int val, cost;
	entry * next;
} *start[N_MAX], *stop[N_MAX], *p;

int n, m, cost[N_MAX], best[N_MAX];

void add(int a, int b, int cost)
{
	p=new entry;
	p->next=NULL;
	p->val=b;
	p->cost=cost;
	if (start[a]==NULL)
	{
		start[a]=p;
		stop[a]=p;
	}
	else
	{
		stop[a]->next=p;
		stop[a]=stop[a]->next;
		
	}
}

int main()
{
	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);
	
	int i, a, b, cst, min, k, nr=0, st=1;
	scanf("%d %d", &n, &m);
	for (i=1; i<=m; i++)
	{
		scanf("%d %d %d", &a, &b, &cst);
		add(a, b, cst);
	}
	
	for (i=1; i<=n; i++)
	{
		cost[i]=INFINIT;
		best[i]=INFINIT;
	}
	cost[st]=0;
	
	while (nr<=n)
	{
		min=INFINIT;
		for (i=1; i<=n; i++)
			if (cost[i]<=min)
			{
				min=cost[i];
				k=i;
			}
		if (cost[k]<best[k])
		{
			best[k]=cost[k];
			p=start[k];
			while(p!=NULL)
			{
				if (( best[k]+p->cost < cost[p->val] ) && (best[p->val]==INFINIT))
					cost[p->val]=best[k]+p->cost;
				p=p->next;
			}
		}
		cost[k]=INFINIT;
		++nr;
		
		
	
	}
	for (i=2; i<=n; i++)
	{
		//printf("de la nodul %d la nodul %d avem drum de cost minim %d\n", st, i, best[i]);
		if (best[i]!=INFINIT)
			printf("%d ", best[i]);
		else printf("0 ");
	}
	fclose(stdout);
	return 0;
}