Cod sursa(job #2833562)

Utilizator RaresRacsanRares Racsan RaresRacsan Data 15 ianuarie 2022 13:23:32
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define SIZE 50010
#define INFINIT 1000001

using namespace std;

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

int n, m, viz[SIZE], d[SIZE], cost, x, y;

vector <pair <int, int>> v[SIZE];
priority_queue <pair <int, int>> q;

void dijkstra(int start)
{
    int cost, nod, k;
    for(int i = 2; i <= n; i++)
        d[i] = INFINIT;

    q.push({0, 1});

    while(!q.empty())
    {
        k = q.top().second;
        q.pop();

        if(viz[k] == 0)
        {
            viz[k] = 1;
            for(auto w : v[k])
            {
                cost =  w.first;
                nod = w.second;
                if(d[nod] > d[k] + cost)
                {
                    d[nod] = d[k] + cost;
                    q.push({-d[nod], nod});
                }
            }
        }
    }

}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        v[x].push_back({cost, y});
    }

    dijkstra(1);

    for(int i = 2; i <= n; i++)
        if(d[i] == INFINIT) fout << 0 << ' ';
        else    fout << d[i] << ' ';
    return 0;
}