Cod sursa(job #2535961)

Utilizator AndreeaGherghescuAndreea Gherghescu AndreeaGherghescu Data 1 februarie 2020 13:16:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <queue>
#define inf 2e9

using namespace std;

ifstream in ("dijkstra.in");
ofstream out ("dijkstra.out");

const int N=50001;
const int M=250001;
int vf[M],urm[M],lst[N],cost[M],nr,n,m,d[N];
priority_queue < pair<int,int> > h;
bool sel[N];

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

int main()
{
    int x,y,c;
    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;
}