Cod sursa(job #381804)

Utilizator totiotot io totio Data 11 ianuarie 2010 17:50:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
using namespace std;
#include <cstdio>
#include <vector>
#define NN 50005
#define INFINIT 1<<30
struct nod{
	int capat,cost;
	nod * next;
};

nod * G[NN];
int n,v[NN],d[NN],t[NN];
int h[NN],nH; //un heap in care memoram nodurile 
int poz[NN]; //poz[k] = poz in heap a nodului k



void addArc(int i,int j,int c){
	nod *p=new nod;
	p->capat=j , p->cost=c;
	p->next=G[i];
	G[i] = p;
}

void Promoveaza(int k){
	int esteHeap=0, aux,i;
	while(!esteHeap && k/2>0){
		i=k/2;
		if(d[h[i]] <= d[h[k]])
			esteHeap=1;
		else{
			aux=h[i],h[i]=h[k],h[k]=aux;
			poz[h[i]]=i, poz[h[k]]=k;
			k=i;
		}
	}
}

void Cerne(int k){
	int esteHeap=0, aux, i;
	while(2*k<=nH && !esteHeap){
		i=2*k;
		if(i+1<=nH && d[h[i]] > d[h[i+1]])
			i=i+1;
		if(d[h[k]]<=d[h[i]])
			esteHeap=1;
		else{
			aux=h[i], h[i]=h[k] , h[k]=aux;
			poz[h[i]]=i, poz[h[k]]=k;
			k=i;
		}
	}
}

void init(int sursa){
	for(int i=0;i<=n;++i)
		v[i]=0,t[i]=-1,d[i]=INFINIT, h[i]=i , poz[i]=i;
	nH=n;
	v[sursa]=1,t[sursa]=0,d[sursa]=0;
	h[sursa]=h[nH--];
	poz[h[sursa]] = sursa;
	Cerne(sursa);
	for(nod *p=G[sursa]; p ; p=p->next){
		t[p->capat]=sursa, d[p->capat]=p->cost;
		Promoveaza(poz[p->capat]);
	}
}

void dijkstra(int sursa){
	init(sursa);
	for(int kkk=1;kkk<n;++kkk){
		int pmin=0;
		pmin=h[1];
		if(d[pmin]==INFINIT)
			break;
		v[pmin]=1;
		h[1]=h[nH--];
		poz[h[1]]=1;
		Cerne(1);
		for(nod* p=G[pmin] ; p ; p=p->next)
				if(v[p->capat]==0)
					if(d[p->capat]>d[pmin]+p->cost){
						d[p->capat] = d[pmin]+p->cost, t[p->capat]=pmin;
						Promoveaza(poz[p->capat]);
					}
				
	
	}
	
}

int main(){
	freopen("dijkstra.in","r",stdin);
	int m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;++i)
		G[i]=NULL;
	
	for( ; m ;--m){
		
		int i,j,c;
		scanf("%d%d%d",&i,&j,&c);
		addArc(i,j,c);
	}
	dijkstra(1);
	
	//for(int i=1;i<=n;++i)
	//	printf("%d ",t[i]);
	freopen("dijkstra.out","w",stdout);
	for(int i=2;i<=n;++i)
		printf("%d ",d[i]!=INFINIT?d[i]:0);
	printf("\n");
	return 0;
}