Cod sursa(job #2391486)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 28 martie 2019 21:43:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;
ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");

struct muchie
{
    int y, c;
};
vector <muchie> v[Nmax];
int h[Nmax], poz[Nmax], d[Nmax], n, m, k, i, x, y, c;

void susheap(int x)
{
    int t=x/2, key=h[x];
    while(t!=0&&d[key]<d[h[t]])
    {
        h[x]=h[t];
        poz[h[x]]=x;
        x=t;
        t=x/2;
    }
    h[x]=key;
    poz[h[x]]=x;
}
void josheap(int i)
{
    int l=2*i, r=2*i+1, urm=i;
    if(l<=k&&d[h[l]]<d[h[urm]])
        urm=l;
    if(r<=k&&d[h[r]]<d[h[urm]])
        urm=r;
    if(urm!=i)
    {
        swap(h[i], h[urm]);
        poz[h[i]]=i;
        poz[h[urm]]=urm;
        josheap(urm);
    }
}
void varf()
{
    h[1]=h[k];
    poz[h[1]]=1;
    k--;
    josheap(1);
}

int main()
{
    fin >> n >> m;
    for(i=1;i<=m;i++)
    {
        fin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    for(i=1;i<=n;i++)
    {
        h[i]=i;
        d[i]=INT_MAX;
        poz[i]=i;
    }
    k=n;
    d[1]=0;
    while(k)
    {
        int nod=h[1];
        if(d[nod]==INT_MAX)
            break;
        varf();
        for(i=0;i<v[nod].size();i++)
            if(d[v[nod][i].y]>d[nod]+v[nod][i].c)
            {
                d[v[nod][i].y]=d[nod]+v[nod][i].c;
                susheap(poz[v[nod][i].y]);
            }
    }
    for(i=2;i<=n;i++)
        if(d[i]==INT_MAX)
            fout << "0 ";
        else
            fout << d[i] << ' ';
    return 0;
}