Cod sursa(job #2377958)

Utilizator DanSDan Teodor Savastre DanS Data 11 martie 2019 15:09:19
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int INF = 5000000001;
const int N = 50001;
const int M = 250001;
int n, m, x, y, c, d[N], sel[N];
vector <pair<int, int> > a[N];
priority_queue<pair<int, int>> h;

void dijkstra(int x0)
{
    for(int i=1; i<=n; i++)
        d[i] = INF;
    d[x0] = 0;
    h.push(make_pair(-d[x0], x0));
    while(!h.empty())
    {
        while(!h.empty() && sel[h.top().second])
            h.pop();
        if(h.empty()) return;
        x = h.top().second;
        sel[x] = true;

        ///for(auto p: a[x])
        for (size_t i = 0; i < a[x].size(); i++)
        {
            y = a[x][i].first;
            c = a[x][i].second;
            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;
        a[x].push_back(make_pair(y, c));
    }
    dijkstra(1);
    for(int i=2; i<=n; i++)
        out<<d[i]<<' ';
    return 0;
}