Cod sursa(job #2535968)

Utilizator rares9991Matisan Rares-Stefan rares9991 Data 1 februarie 2020 13:19:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <queue>
using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int N=50001;

const int M=250001;

const int INF=1e9;

int lst[N], vf[M], urm[M], q[N+5], nr, d[N], cst[M], nrq[N], dr=-1, st,x,y,c,n,m;
bool sel[N];

priority_queue<pair<int,int> > h;

void adauga(int x, int y, int c)
{
    vf[++nr]=y;
    cst[nr]=c;
    urm[nr]=lst[x];
    lst[x]=nr;
}

void dijkstra(int x0)
{
    for(int i=1; i<=n; i++)
    {
        d[i]=INF;
        sel[i]=false;
    }
    d[x0]=0;
    h.push(make_pair(0,x0));
    while(!h.empty())
    {
        while(!h.empty() and sel[h.top().second])
        {
            h.pop();
        }
        if(h.empty())
        return;
        x=h.top().second;
        sel[x]=true;
        for(int p=lst[x]; p!=0; p=urm[p])
        {
            y=vf[p];
            c=cst[p];
            if(d[x]+c<d[y])
            {
            d[y]=d[x]+c;
            h.push(make_pair(-d[y],y));
            }
        }
    }
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y>>c;
        adauga(x,y,c);
    }
    dijkstra(1);
    for(int i=2; i<=n; i++)
    {
        if(d[i]!=INF)
        out<<d[i]<<" ";
        else
        out<<0<<" ";
    }
    return 0;

}