Cod sursa(job #1712131)

Utilizator antanaAntonia Boca antana Data 2 iunie 2016 09:25:32
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <cstdio>
#define MAXM 250000
#define MAXN 50000
#define INF (1<<30)
using namespace std;
struct muchie{
    int val, d;
}v[MAXM+1];
int lista[MAXN+1], next[MAXM+1], r;
int heap[MAXN+1], dist[MAXN+1], poz[MAXN+1], k;
inline int adauga(int x, int y, int l)
{
    v[++r].val=y;
    v[r].d=l;
    next[r]=lista[x];
    lista[x]=r;
}
inline int father(int x){return x/2;}
inline int son_left(int x){ return x*2;}
inline int son_right(int x){ return x*2+1;}
inline void swap1(int a, int b)
{
    int aux=heap[a];
    poz[heap[a]]=b;
    poz[heap[b]]=a;
    heap[a]=heap[b];
    heap[b]=aux;
}
inline void up(int x)
{
    int p, f=1;
    while(father(x) && f)
    {
        f=0;
        p=father(x);
        if(dist[heap[p]] > dist[heap[x]])
        {
            f=1;
            swap1(p, x);
        }
        x=p;
    }
}
inline void down(int x)
{
    int p, q, f=1;
    while(son_left(x)<=k && f)
    {
        f=0;
        p=son_left(x);
        q=son_right(x);
        if(q <=k && dist[heap[q]] < dist[heap[p]])
            p=q;
        if(dist[heap[p]] < dist[heap[x]])
        {
            f=1;
            swap1(p, x);
        }
        x=p;
    }
}
inline void add(int nod)
{
    heap[++k]=nod;
    poz[nod]=k;
    up(k);
}
inline void delete1()
{
    swap1(1, k);
    k--;
}
void dijkstra_heap()
{
    int p, nod, vecin;
    add(1);
    while(k)
    {
        nod=heap[1];
        delete1();
        p=lista[nod];
        while(p)
        {
            vecin=v[p].val;
            if(dist[vecin] > dist[nod]+v[p].d)
            {
                dist[vecin] = dist[nod]+v[p].d;
                if(poz[vecin]!=-1)
                    up(poz[vecin]);
                else add(vecin);
            }
            p=next[p];
        }
    }
}
int main()
{
    freopen("dijkstra.in", "r",stdin);
    freopen("dijkstra.out", "w",stdout);
    int n, m, x, y, l;
    scanf("%d%d", &n, &m);
    for(int i=1;i<=m; ++i)
    {
        scanf("%d%d%d", &x,&y, &l);
        adauga(x, y, l);
    }
    for(int i=1;i<=n;++i)
    {
        poz[i]=-1;
        dist[i]=INF;
    }
    dist[1]=0;
    dijkstra_heap();
    for(int i=2;i<=n;++i)
    {
        if(dist[i]==INF)
            printf("0 ");
        else printf("%d ", dist[i]);
    }
    return 0;
}