Cod sursa(job #2354870)

Utilizator vladuteluVlad Oancea vladutelu Data 25 februarie 2019 17:25:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;


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

vector <pair<int, int> > G[50005];

int INF = 0x3f3f3f3f;

int d[50005];
int main()
{
    int n, m, from, to, cost;
    in>>n>>m;
    for(int i = 1; i<=m; i++)
    {
        in>>from>>to>>cost;
        G[from].push_back(make_pair(to, cost));
    }

    for(int i = 0; i<50005; i++)
        d[i] = INF;

    d[1] = 0;

    set< pair<int, int> > h;
    h.insert(make_pair(0, 1));
    while(!h.empty())
    {
        int nod = (*h.begin()).second;
        h.erase(h.begin());
        for(int i = 0; i<G[nod].size(); ++i)
        {
            int to = G[nod][i].first;
            int cost = G[nod][i].second;
            if(d[to] > d[nod] + cost)
            {
                if(d[to]!=INF)
                    h.erase(h.find(make_pair(d[to], to)));
                d[to] = d[nod] + cost;
                h.insert(make_pair(d[to], to));
            }
        }
    }

    for(int i = 2; i<=n; i++)
    {
        if(d[i]==INF)
            d[i] = 0;
        out<<d[i]<<" ";
    }
    return 0;
}