Cod sursa(job #1277639)

Utilizator LycrsTrifan Tamara Lycrs Data 27 noiembrie 2014 22:37:40
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

const int inf=999999999;

typedef struct celula{
                int nod, cost;
                celula *next;}
                *lista;
int L=1, i, k, m, n, a, b, c, x, H[50005], D[50005];
lista lda[50005], r;

void add(int b, int c, lista &y){
    lista p=new celula;
    p->nod=b;
    p->cost=c;
    p->next=y;
    y=p;
}

void down( int k)
{
    int nod=1;
    do{
        nod=0;
        if (k*2<=L)
        {nod=k*2;
        if (k*2<L && D[H[k*2+1]]<D[H[k*2]]) nod=k*2+1;
        if (D[H[nod]]>=D[H[k]]) nod=0; }

        if (nod)
        {   swap(H[k], H[nod]);
            k=nod;
        }

    }while(nod);
}

void up(int k)
{
    while (k>1 && D[H[k]]<D[H[k/2]])
    {
        swap(H[k], H[k/2]);
        k/=2;
    }
}

int main()
{
    cin>>n>>m;

    for (i=1; i<=m; ++i)
    {
        cin>>a>>b>>c;
        add(b, c, lda[a]);
    }


    for (i=2; i<=n; ++i) D[i]=inf;
    H[1]=1;

    while (L){
        k=H[1];
        r=lda[k];
        H[1]=H[L];
        --L;
        down(1);
        while (r) {
            if (D[k]+r->cost < D[r->nod]){
                D[r->nod]=D[k]+r->cost;
                H[++L]=r->nod;
                up(L);
            }
            r=r->next;
        }
    }

    for (i=2; i<=n; ++i) if (D[i]==inf) cout<<"0 "; else cout<<D[i]<<" ";
    return 0;
}