Cod sursa(job #2194516)

Utilizator DovlecelBostan Andrei Dovlecel Data 13 aprilie 2018 17:44:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
using namespace std;
const int N=50010;
const int INF = (1 << 30);
vector<int>a[N];
vector<int>c[N];
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int h[N],nr,poz[N],n,m,d[N];
void urca(int p)
{
    while(p>1 && d[h[p]]<d[h[p/2]])
    {
        swap(h[p],h[p/2]);
        swap(poz[h[p]],poz[h[p/2]]);
        p=p/2;
    }
}

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

}
void sterge(int p)
{
    swap(h[p],h[nr]);
    swap(poz[h[p]],poz[h[nr]]);
    nr--;
    coboara(p);
}

int main()
{
    int x,y,cost;
    in>>n>>m;
    for(int i=1;i<=m;i++)
    {
        in>>x>>y>>cost;
        a[x].push_back(y);
        c[x].push_back(cost);
    }
    d[1]=0;
    for(int i=2;i<=n;i++)
        d[i]=INF;
    nr=n;
    for(int i=1;i<=n;i++)
    {
        h[i]=i;
        poz[i]=i;
    }
    while(nr>1 && d[h[1]]<INF)
    {
        x=h[1];
        sterge(1);
        for(unsigned i=0;i<a[x].size();i++)
        {
            y=a[x][i];
            cost=c[x][i];
            if(d[x]+cost<d[y])
            {
                d[y]=d[x]+cost;
                urca(poz[y]);
            }
        }
    }
    for(int i=2;i<=n;i++)
    {
        if(d[i]==INF)
            out<<'0'<<' ';
        else
            out<<d[i]<<' ';
    }
    return 0;
}