Cod sursa(job #2830803)

Utilizator Madalin_IonutFocsa Ionut-Madalin Madalin_Ionut Data 10 ianuarie 2022 11:40:24
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#define oo 2000000003

using namespace std;

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

struct drum
{
    int cost, nod;

    bool operator<(const drum A) const
    {
        return cost < A.cost;
    }
};

int n, m;
vector<drum> h[50003];
priority_queue<drum> q;
int viz[50003];
int d[50003];

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

void Dijkstra(int P)
{
    int i, k, c;
    for(i = 1;i <= n;i++)
        d[i] = oo;
    q.push({ 0, P });
    d[P] = 0;
    while(!q.empty())
    {
        k = q.top().nod;
        q.pop();
        if(viz[k] == 0)
        {
            viz[k] = 1;
            for(auto w : h[k])
            {
                i = w.nod;
                c = w.cost;
                if(d[i] > d[k] + c)
                {
                    d[i] = d[k] + c;
                    q.push({ -d[i], i});
                }
            }
        }
    }
}

int main()
{
    Citire();
    Dijkstra(1);
    for(int i = 2;i <= n;i++)
        fout << d[i] << " ";
    fout.close();
    return 0;
}