Cod sursa(job #2240502)

Utilizator EricEric Vilcu Eric Data 13 septembrie 2018 17:11:05
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <fstream>
#include <iostream>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n,m;
struct laturi {int dest,cost;laturi *next;} *a[50002];
//dm=drum minim,h=inaltime,poz=pozitia in H,pz=pozitie max
//astfel,h[i]-nodul de pe poz i
//poz[h[i]]=i;
//dm[h[i]]=drumu minim al nodului de pe poz i
int pih[50002],h[50002],dm[50002],pz;
//x=plecare,y=destinatar,z=cost
void adauglat(int x,int y,int z)
{
    laturi *nou=new laturi;
    nou->cost=z;
    nou->dest=y;
    nou->next=a[x];
    a[x]=nou;
}
void downem(int pzt)
{
    if(pzt*2<=pz)
    {
        if(dm[h[pzt*2]]<dm[h[pzt]])if(pzt*2+1>pz||dm[h[pzt*2]]<dm[h[pzt*2+1]])
        {
            swap(h[pzt*2],h[pzt]);
            swap(pih[h[pzt*2]],pih[h[pzt]]);
            downem(pzt*2);
        }
        if(pzt*2+1<=pz)if(dm[h[pzt*2+1]]<dm[h[pzt]])
        {
            swap(h[pzt*2+1],h[pzt]);
            swap(pih[h[pzt*2+1]],pih[h[pzt]]);
            downem(pzt*2+1);
        }
    }
}
void upem(int pzt)
{
    if(pzt!=1)if(dm[h[pzt/2]]>dm[h[pzt]])
    {
        swap(h[pzt/2],h[pzt]);
        swap(pih[h[pzt/2]],pih[h[pzt]]);
        upem(pzt/2);
    }
}
void addneighbours(int q)
{
    int c,d,numer=0;
    while (a[q]!=NULL)
    {
        c=a[q]->cost;
        d=a[q]->dest;
        if(dm[d]>c)
        {
            if(dm[d]==20009){h[++pz]=d;pih[d]=pz;}
            dm[d]=c+dm[q];
            upem(pih[d]);
        }
        a[q]=a[q]->next;
        if(a[q]==NULL)break;
        ++numer;
    }
}
int main()
{
    f>>n>>m;
    for(int i=1;i<=m;++i)
    {
        int x,y,z;
        f>>x>>y>>z;
        adauglat(x,y,z);
        adauglat(y,x,z);
    }
    for(int i=2;i<=n;++i){dm[i]=20009;pih[i]=-1;}
    pz=1;
    dm[1]=0;
    pih[1]=1;
    h[1]=1;
    while(pz!=0)
    {
        addneighbours(h[1]);
        swap(h[1],h[pz]);
        --pz;
        downem(1);
    }
    for(int i=2;i<=n;++i){if(dm[i]!=20009)g<<dm[i]<<" ";
                         else g<<"0 ";}
}