Cod sursa(job #1004438)

Utilizator timicsIoana Tamas timics Data 2 octombrie 2013 18:45:00
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include<stdio.h>
const int inf = 1 << 30;

int m,n,d[50010],h[50010],poz[50010],k;

struct graf
{
    int nod,cost;
    graf *next;
};

graf *a[50010];

void swap(int x, int y)
{
    int aux=h[x];
    h[x]=h[y];
    h[y]=aux;
}

void upheap(int x)
{
    while(x>1 && d[h[x/2]]>d[h[x]])
    {
        swap(x,x/2);
        poz[h[x]]=x;
        poz[h[x/2]]=x/2;
        x=x/2;
    }
}

void downheap(int x)
{
    int y;
    while(x!=y)
    {
        y=x;
        if(2*x<=k && d[h[x]]>=d[h[2*y]])
            x=2*y;
        if(2*x+1<=k && d[h[x]]>=d[h[2*y+1]])
            x=2*y+1;

        swap(x,y);
        poz[h[x]]=x;
        poz[h[y]]=y;
    }
}

void dijkstra_heap()
{
    for(int i=2;i<=n;++i)
    {
        d[i]=inf;
        poz[i]=-1;
    }
    poz[1]=1;

    h[++k]=1;

    while(k)
    {
        int min=h[1];
        swap(1,k);
        poz[h[1]]=1;
        --k;

        downheap(1);

        graf *q = a[min];

        while(q)
        {
            if(d[q->nod]>d[min]+q->cost)
            {
                d[q->nod] = d[min] + q->cost;

                if(poz[q->nod]!=-1)
                    upheap(poz[q->nod]);
                else
                {
                    h[++k] = q->nod;
                    poz[h[k]] = k;
                    upheap(k);
                }
            }
            q=q->next;

        }
    }
}

int main()
{
    //freopen("input.in","r",stdin);
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    scanf("%d%d",&n,&m);
    int x,y,z;
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d%d",&x,&y,&z);
        graf *q = new graf;
        q->nod = y;
        q->cost = z;
        q->next = a[x];
        a[x] = q;
    }
    dijkstra_heap();

    for(int i=2;i<=n;++i)
    {
        if(d[i]==inf)
            printf("%d",0);
        else
            printf("%d ",d[i]);
    }
    return 0;
}