Cod sursa(job #3138499)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 19 iunie 2023 21:06:13
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;
using llx = long long;

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

const int inf = 1'000'000'000;

struct el
{
    int nod, c;
    bool operator<(const el &alt) const
    {
        return c > alt.c;
    }
};

vector<vector<pair<int, int>>> v;
vector<int> dist;
priority_queue<el> p;

int main()
{
    int n, m, i, x, y, z; 
    el na;

    fin >> n >> m;
    v.resize(n+1);
    dist.assign(n+1, inf);
    for (i = 1; i<=m; i++)
    {
        fin >> x >> y >> z;
        v[x].push_back({y, z});
    }

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

    for (i = 1; i<n; i++)
    {
        while (p.empty() == 0 && p.top().c > dist[p.top().nod])
            p.pop();
        if (p.empty() == 1)
            break;

        na = p.top();
        p.pop();

        for (const auto &nv : v[na.nod])
        {
            tie(x, y) = nv;
            if (dist[x] > na.c + y)
            {
                dist[x] = na.c + y;
                p.push({x, dist[x]});
            }
        }
    }

    for (i = 2; i<=n; i++)
    {
        if (dist[i] == inf)
            fout << 0 << ' ';
        else
            fout << dist[i] << ' ';
    }
    return 0;
}