Cod sursa(job #2190983)

Utilizator Narvik13Razvan Roatis Narvik13 Data 1 aprilie 2018 11:30:27
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 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,dist[NMAX];
vector <pair<int,int>> g[NMAX];
priority_queue <pair<int,int>> pq;

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

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

    pq.push({0,1});

    int nod;
    while(not pq.empty())
    {
        nod = pq.top().second;
        pq.pop();

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

void output()
{
    for(int i = 2; i <= n; ++i)
        o << (dist[i] == INF ? 0 : dist[i]) << ' ';
}

int main()
{
    input();
    dijkstra();
    output();
    return 0;
}