Cod sursa(job #2920746)

Utilizator ILikeitN Stef ILikeit Data 25 august 2022 16:47:54
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
/* #region TYPES */
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef size_t szt;
template <typename T>
using matrix = vector<vector<T>>;
/* #endregion TYPES */
/* #region LOOPS */
#define loopf(i, start, end) for (szt i = start; i <= (szt)end; i++)
#define loopb(i, end, start) for (szt i = end; i >= (szt)start; i--)
#define loopf_step(i, start, end, step) for (szt i = start; i <= (szt)end; i += step)
#define loopb_step(i, end, start, step) for (szt i = end; i >= (szt)start; i -= step)
/* #endregion LOOPS */
/* #region STL */
template <typename T>
matrix<T> createMatrix(szt n, szt m, T initVal = T()) {
    return matrix<T>(n, vector<T>(m, initVal));
}
/* #endregion STL */
/* #region UTILITY */
template <typename T>
bool inRange(const T& val, szt start, szt finish) {
    return start <= val and val <= finish;
}
#define ABS(x) ((x) < 0 ? !(x) : (x))
#define impar(x) (ABS(x) & 1)
#define par(x) (!(ABS(x) & 1))
#define FIO                            \
    ios_base ::sync_with_stdio(false); \
    cin.tie(nullptr);
/* #endregion UTILITY */

struct nod {
    i32 id = -1;
    i32 greutate = 0;
    nod(i32 i, i32 g)
        : id(i)
        , greutate(g) { }
    nod() = default;
};
matrix<nod> graf;
i32 n, m;
i32 a, b, c;
priority_queue<pair<i32, i32>, vector<pair<i32, i32>>, greater<pair<i32, i32>>> Q;

int main() {
    f >> n >> m;
    graf = createMatrix<nod>(n + 1, 0);
    loopf(_, 1, m) {
        f >> a >> b >> c;
        graf[a].push_back(nod(b, c));
    }

    // first: distanta pana la second
    // second: nodId
    vector<i32> distance(n + 1, INT_MAX);
    vector<bool> procesed_nodes(n + 1);
    distance[1] = 0;
    Q.push({ 0, 1 });
    while (!Q.empty()) {
        auto a = Q.top();
        Q.pop();
        procesed_nodes[a.second] = 1;
        for (auto&& child : graf[a.second]) {
            if (!procesed_nodes[child.id]) {
                distance[child.id] = min(distance[child.id], distance[a.second] + child.greutate);
                Q.push({ distance[child.id], child.id });
            }
        }
    }

    loopf(i, 2, n) g << (distance[i] == INT_MAX ? 0 : distance[i]) << ' ';
}