Cod sursa(job #370999)

Utilizator titusuTitus C titusu Data 2 decembrie 2009 23:15:09
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <cstdio>
using namespace std;
#define MAX 50050
#define INFINIT 2000000000
struct muchie{
	int cost, capat;
	muchie *next;
};

muchie *a[MAX];
int d[MAX],n;

void read(){
	freopen("dijkstra.in","r",stdin);
	int i,j,cost,m;
	scanf("%d%d", &n,&m);
	muchie *p;
	for( ; m ;--m){
		scanf("%d%d%d", &i,&j,&cost);
		p = new muchie;
		p->capat = j;
		p->cost = cost;
		p->next = a[i];
		a[i] = p;
	}
}

void bellman_ford(int start){
	for(int i=1;i<=n;i++)
		d[i]=INFINIT;
	d[start]=0;
	for(int i =1;i<n;i++)
		for(int j=1;j<=n;j++)
			for(muchie * p = a[j]; p ; p = p->next)
				if( d[p->capat] > d[j] + p->cost)
					d[p->capat] = d[j] + p->cost;
					
}

void write(){
	freopen("dijkstra.out","w",stdout);
	for(int i = 2 ; i<=n;i++)
		printf("%d ", d[i] == INFINIT ? 0 : d[i]);
}

int main(){
	read();
	bellman_ford(1);
	write();
	return 0;
}