Cod sursa(job #2843480)

Utilizator seburebu111Mustata Dumtru Sebastian seburebu111 Data 2 februarie 2022 15:49:45
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 50001;
const int M = 250001;
const int INF=1e9+1;

struct element{
    int vf, c, urm;
} 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;
    }
}

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;
        h[++nh] = i;
        poz[i]=nh;
    }
    d[x0] = 0;
    urca(poz[x0]);
    while(nh>0 && d[h[1]] < INF)
    {
        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;
                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;
}