Cod sursa(job #502457)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 19 noiembrie 2010 16:30:16
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include<cstdio>
#include<cstring>

using namespace std;

#define Nmax 50001

#define INF 0x3f3f3f3f

int N, M, D[Nmax];
char U[Nmax];

struct graf {
	int nod, cost;
	graf *next;
} *G[Nmax];

void add(int where, int what, int cost) {
	graf *q=new graf;
	q->nod=what;
	q->cost=cost;
	q->next=G[where];
	G[where]=q;
}

void dijkstra() {
	int i, min, nod;
	graf *t;
	memset(D,INF,sizeof(D));
	D[1]=0;
	
	while(1) {
		min=INF; nod=-1;
		for(i=1; i<=N; i++)
			if(!U[i] && D[i]<min) {
				min=D[i];
				nod=i;
			}
		if(min==INF)
			break;
		U[nod]=1; 
		for(t=G[nod]; t; t=t->next) 
			if(D[t->nod]>D[nod]+t->cost)
				D[t->nod]=D[nod]+t->cost;
	}
}

int main() {
	freopen("dijkstra.in","r",stdin);
	freopen("dijkstra.out","w",stdout);
	
	int i, j, c;
	scanf("%d %d",&N,&M);
	while(M--) {
		scanf("%d %d %d",&i,&j,&c);
		add(i,j,c);
	}
	
	dijkstra();
	
	for(i=2; i<=N; i++)
		printf("%d ",D[i]);
	printf("\n");
	
	return 0;
}