Cod sursa(job #2166308)

Utilizator UnseenMarksmanDavid Catalin UnseenMarksman Data 13 martie 2018 16:33:20
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include <cstdio>
#include <vector>
#define NMAX 50002
#define Inf 2000000000
using namespace std;

int n, m, k;
int h[NMAX], pos[NMAX], d[NMAX];
vector<pair<int,int>>A[NMAX];

void read()
{
    int x,y,c;
    scanf("%d %d", &n, &m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d %d", &x, &y, &c);
        A[x].push_back({y,c});
    }
}

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

void downheap(int x)
{
    int f, what=x;
    while(what<=k)
    {
        f=what;
        if(what*2<=k)
        {
            f=what*2;
            if(f+1<=k)
            {
                if(d[h[f+1]]<d[h[f]])
                {
                    f++;
                }
            }
        }
        else
            return;

        if(d[h[what]]>d[h[f]])
        {
            pos[h[what]]=f;
            pos[h[f]]=what;
            swapheap(what,f);
            what=f;
        }
        else
            return;
    }
}

void upheap(int x)
{
    int tata, what=x;
    while(what>1)
    {
        tata=what/2;
        if(d[h[tata]]>d[h[what]])
        {
            pos[h[what]]=tata;
            pos[h[tata]]=what;

            swapheap(tata,what);
            what=tata;
        }
        else
            return;
    }
}

void dijkstra_heap()
{
    for(int i=2; i<=n; i++)
    {
        d[i]=Inf;
        pos[i]=-1;
    }
    pos[1]=1;
    h[++k]=1;
    while(k)
    {
        int nod=h[1];
        swapheap(1,k);
        pos[h[1]]=1;
        k--;

        downheap(1);

        for(auto w:A[nod])
        {
            if(d[w.first]>d[nod]+w.second)
            {
                d[w.first]=d[nod]+w.second;

                if(pos[w.first]!=-1)
                {
                    upheap(pos[w.first]);
                }
                else
                {
                    h[++k]=w.first;
                    pos[h[k]]=k;
                    upheap(k);
                }
            }
        }
    }
}

void write()
{
    for(int i=2; i<=n; i++)
    {
        if(d[i]!=Inf)
        {
            printf("%d ", d[i]);
        }
        else
        {
            printf("0 ");
        }
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);

    read();
    dijkstra_heap();
    write();

    return 0;
}