Cod sursa(job #278754)

Utilizator GagosGagos Radu Vasile Gagos Data 12 martie 2009 15:05:39
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include<stdio.h>
using namespace std;  
typedef struct nod
{
	long info;
	long dist;
	nod *next;
}*pnod;   
pnod prim[50002],pp;   
long int n,m,i,a,b,c,i8,lh,nv,dv,nn,dn,aux;
long int h[50002],ph[50002],d[50002],viz[50002];
void add(pnod &p,long j,long c)
{   
    nod *q=new nod;   
    q->info=b;   
    q->dist=c;   
    q->next=p;
	p=q;
}
void hd(long int ic)   
{   
    long int is,is1;   
    is=ic<<1;
	is1=is|1;   
    if(is>lh)
		return;   
    if(is<lh)
		if(d[h[is1]]<d[h[is]])
			is=is1;   
    if(d[h[is]]<d[h[ic]])
	{
		aux=h[is];
		h[is]=h[ic];
		h[ic]=aux;   
		ph[h[is]]=is;
		ph[h[ic]]=ic; 
		hd(is);
	}   
}
void hu(long int ic)
{   
    long int is;   
    is=ic>>1;   
    if(!is)
		return;   
    if(d[h[is]]>d[h[ic]])
	{
		aux=h[is];
		h[is]=h[ic];
		h[ic]=aux;   
		ph[h[is]]=is;
		ph[h[ic]]=ic; 
		hu(is);
	}   
}

int main()   
{   
    freopen("dijkstra.in","r",stdin);
	freopen("dijkstra.out","w",stdout);
	scanf("%ld %ld",&n,&m);
	for(i=1;i<=m;i++)
	{
		scanf("%ld %ld %ld",&a,&b,&c);
		add(prim[a],b,c);
	}
    i8=1000000000;   
    for(i=1;i<=n;i++)
	{
		h[i]=i;
		ph[i]=i;
		d[i]=i8;
	}
	d[1]=0;
	lh=n;   
    while(lh && d[h[1]]<i8)
	{
		nv=h[1];
		viz[nv]=1;
		dv=d[nv];
		h[1]=h[lh];
		ph[h[1]]=1;
		lh--;
		hd(1);
		pp=prim[nv];
		while(pp)
		{
			if(viz[pp->info])
				pp=pp->next;
			else
			{
				if(d[pp->info]>dv+pp->dist)
				{
					d[pp->info]=dv+pp->dist;
					hu(ph[pp->info]);
				}
				pp=pp->next;
			}
		}
	}
	for(i=2;i<=n;i++)
	{
		if(d[i]==i8)
			d[i]=0;
		printf("%ld ",d[i]);
	}   
    printf("\n");
	return 0;   
}