Cod sursa(job #2275492)

Utilizator stefantagaTaga Stefan stefantaga Data 3 noiembrie 2018 11:29:30
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int mini[50001];
vector <pair <int,int > > v[50005];
priority_queue <pair <int,int> ,vector <pair <int,int> > ,greater <pair <int,int> > > h;
int n,m,i,x,y,cost,sel[50005],nr,c,j;
int main()
{
    f>>n>>m;
    for (i=1;i<=m;i++)
    {
        f>>x>>y>>cost;
        v[x].push_back({y,cost});
    }
    for (i=2;i<=n;i++)
    {
        mini[i]=-1;
    }
    mini[1]=0;
    sel[1]=1;
    for (i=0;i<v[1].size();i++)
    {
        h.push({v[1][i].second,v[1][i].first});
        mini[v[1][i].first]=v[1][i].second;
    }
    nr=v[1].size();
    while (nr!=0)
    {
        while (sel[h.top().second]==1)
        {
            h.pop();
        }
        c=h.top().second;
        sel[c]=1;
        h.pop();
        nr--;
        for (i=0;i<v[c].size();i++)
        {
            j=v[c][i].first;
            if (mini[j]==-1)
            {
                nr++;
                mini[j]=mini[c]+v[c][i].second;
                h.push({mini[j],v[c][i].first});
            }
            else
            if (mini[j]>mini[c]+v[c][i].second)
            {
                mini[j]=mini[c]+v[c][i].second;
                h.push({mini[j],j});
            }
        }
    }
    for (i=2;i<=n;i++)
    {
        if (mini[i]==-1)
        {
            g<<"0"<<" ";
        }
        else
        {
            g<<mini[i]<<" ";
        }
    }
    return 0;
}