Cod sursa(job #2844123)

Utilizator Davla2Stancu Vlad Davla2 Data 3 februarie 2022 19:54:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>

using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

const int N=50001;
const int M=250001;
const int INF=1000000001;

struct element{
    int vf,c,urm;
};

element v[M];
int lst[N],d[N],h[N],poz[N],n,m,nr,nh;

void adauga_succesor(int x, int y, int c)
{
    nr++;
    v[nr].vf=y;
    v[nr].c=c;
    v[nr].urm=lst[x];
    lst[x]=nr;
}

void schimb(int p1, int p2)
{
    int aux=h[p1];
    h[p1]=h[p2];
    h[p2]=aux;
    poz[h[p1]]=p1;
    poz[h[p2]]=p2;
}

void urca(int p)
{
    while(p>1 && d[h[p]]<d[h[p/2]])
    {
        schimb(p, p/2);
        p/=2;
    }
}

void coboara(int p)
{
    int fs=2*p,fd =2*p+1,bun=p;
    if(fs<=nh && d[h[fs]]<d[h[bun]])
    {
        bun=fs;
    }
    if(fd<= nh && d[h[fd]]<d[h[bun]])
    {
        bun=fd;
    }
    if(bun!=p)
    {
        schimb(bun, p);
        coboara(bun);
    }
}

void sterge(int p)
{
    if(p==nh)
    {
        nh--;
    }
    else
    {
        h[p]=h[nh--];
        poz[h[p]]=p;
        urca(p);
        coboara(p);
    }
}

void dijkstra(int x0)
{
    for(int i=1; i<=n; i++)
    {
        d[i]=INF;
    }
    d[x0]=0;
    h[++nh]=x0;
    poz[x0]=nh;
    while(nh>0)
    {
        int x=h[1];
        sterge(1);
        for(int p=lst[x]; p!=0; p=v[p].urm)
        {
            int y=v[p].vf;
            int c=v[p].c;
            if(d[x]+c<d[y])
            {
                d[y]=d[x]+c;
                if(poz[y]==0)
                {
                    h[++nh]=y;
                    poz[y]=nh;
                }
                urca(poz[y]);
            }
        }
    }
}

int main()
{

    in>>n>>m;
    for(int i=0; i<m; i++)
    {
        int x,y,c;
        in>>x>>y>>c;
        adauga_succesor(x, y, c);
    }
    dijkstra(1);
    for(int i=2; i<=n; i++)
    {
        if(d[i]==INF)
        {
            d[i]=0;
        }
        out<<d[i]<<" ";
    }
    return 0;
}