Cod sursa(job #389650)

Utilizator cristikIvan Cristian cristik Data 1 februarie 2010 23:36:05
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <stdio.h>
#include <string.h>
#define max 50010
const int inf=10000;
struct lista
{
    int nod,cost;
    lista *next;
};
lista *g[max],*p;
int h[max],d[max],poz[max],min,c,i,j,n,m,lg;
void push(int i,int j,int c)
{
    lista *p=new lista;
    p->nod=j;
    p->cost=c;
    p->next=g[i];
    g[i]=p;
}
void swap(int i,int j)
{
    int t=h[i]; h[i]=h[j]; h[j]=t;
}
void upheap(int x)
{
    while(x/2 && d[h[x]]<d[h[x/2]])
    {
        swap(x,x/2);
        poz[h[x]]=x;
        poz[h[x/2]]=x/2;
        x/=2;
    }
}
void downheap(int x)
{
    int y=0;
    while(x!=y)
    {
        y=x;
        if(2*y<=lg && d[h[x]]>d[h[y*2]]) x=y*2;
        if(2*y+1<=lg && d[h[x]]>d[h[y*2+1]]) x=y*2+1;
        swap(x,y);
        poz[h[x]]=x;
        poz[h[y]]=y;
    }
}
void remove()
{
    swap(1,lg);
    poz[h[1]]=1;
    lg--;
    downheap(1);
}
void insert(int x)
{
    h[++lg]=x;
    poz[h[lg]]=lg;
    upheap(lg);
}
int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(; m--; )
    {
        scanf("%d%d%d",&i,&j,&c);
        push(i,j,c);
    }
    memset(d,inf,sizeof(d));
    d[1]=0;
    insert(1);

    while(lg)
    {
        min=h[1];
        remove();
        for(p=g[min]; p!=NULL; p=p->next)
         if(d[p->nod]>d[min]+p->cost)
         {
             d[p->nod]=d[min]+p->cost;
             if(poz[p->nod]) upheap(poz[p->nod]);
             else insert(p->nod);
         }
    }
    for(i=2; i<=n; i++)
     if(d[i]!=inf) printf("%d ",d[i]);
     else printf("0 ");
    return 0;
}