Cod sursa(job #3135077)

Utilizator Mihai_PopescuMihai Popescu Mihai_Popescu Data 1 iunie 2023 18:47:12
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

#define NMAX 50005

vector<pair<int, int >> v[NMAX];

priority_queue<pair<int, int>> PQ;

int dist[NMAX], viz[NMAX];

int main()
{
    int n, m;
    fin >> n >> m;

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

    for (int i = 2; i <= n; ++ i)
        dist[i] = INT_MAX;

    dist[1] = 0;
    PQ.push({0, 1});

    while (!PQ.empty())
    {
        auto aux = PQ.top();
        PQ.pop();

        int nod = aux.second;
        if (!viz[nod])
        {
            viz[nod] = 1;
            for (auto it : v[nod])
                if (dist[nod] + it.second < dist[it.first])
                {
                    dist[it.first] = dist[nod] + it.second;
                    PQ.push({-dist[it.first], it.first});
                }
        }
    }

    for (int i = 2; i <= n; ++ i)
    {
        if (dist[i] == INT_MAX)
            dist[i] = 0;

        fout << dist[i] << ' ';
    }
    return 0;
}