Cod sursa(job #2985900)

Utilizator AswVwsACamburu Luca AswVwsA Data 27 februarie 2023 12:39:39
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;

const int NMAX = 500000;

vector <pair <int, int> > g[NMAX + 1];
int d[NMAX + 1];

struct ob
{
    int cost;
    int nod;
};

bool operator <(ob a, ob b)
{
    return a.cost > b.cost;
}

priority_queue <ob> pq;

int main()
{
    ifstream cin("dijkstra.in");
    ofstream cout("dijkstra.out");
    int n, m, i;
    cin >> n >> m;
    while (m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        g[a].push_back({b, c});
    }
    for (i = 2; i <= n; i++)
        d[i] = INT_MAX;
    pq.push({0, 1});
    while (!pq.empty())
    {
        ob f = pq.top();
        pq.pop();
        if (d[f.nod] < f.cost)
            continue;
        d[f.nod] = f.cost;
        for (pair <int, int> u : g[f.nod])
            if (d[u.first] > d[f.nod] + u.second)
            {
                d[u.first] = d[f.nod] + u.second;
                pq.push({d[u.first], u.first});
            }
    }
    for (i = 2; i <= n; i++)
    {
        if (d[i] == INT_MAX)
            d[i] = 0;
        cout << d[i] << " ";
    }
}