Cod sursa(job #2206896)

Utilizator Burbon13Burbon13 Burbon13 Data 24 mai 2018 10:24:56
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50002
#define INF 0x3f3f3f3f

using namespace std;

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

int n,m;
vector <pair<int,int>> g[NMAX];
int dist[NMAX];
priority_queue <pair<int,int>> q;

void citire()
{
    f >> n >> m;
    int x,y,c;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y >> c;
        g[x].push_back({y,c});

    }
}

void dijkstra()
{
    for(int i = 2; i <= n; ++i)
        dist[i] = INF;

    q.push({0,1});
    while(not q.empty())
    {
        int nod = q.top().second;
        int d = - q.top().first;
        q.pop();

        if(dist[nod] != d)
            continue;

        for(auto i: g[nod])
            if(dist[i.first] > dist[nod] + i.second)
            {
                dist[i.first] = dist[nod] + i.second;
                q.push({-dist[i.first],i.first});
            }
    }
}

void afis()
{
    for(int i = 2; i <= n; ++i)
        if(dist[i] == INF)
            o << "0 ";
        else
            o << dist[i] << ' ';
}

int main()
{
    citire();
    dijkstra();
    afis();
    return 0;
}