Cod sursa(job #2844122)

Utilizator VipioanaMirea Oana Teodora Vipioana Data 3 februarie 2022 19:53:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#define INF 1000000001
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int N=5e4+1;
const int M=25e4+1;
int n,m;
int lst[N],d[N],h[N],poz[N],nr,nh;

struct ura{
    int vf,c,urm;
}v[M];

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()
{
    f>>n>>m;
    for(int i=1; i<=m; i++){
        int x,y,c;
        f>>x>>y>>c;
        adauga_succesor(x,y,c);
    }
    dijkstra(1);
    for(int i=2; i<=n; i++){
        if(d[i]==INF)
            d[i]=0;
        g<<d[i]<<" ";
    }
    return 0;
}