Cod sursa(job #3251669)

Utilizator Vlad3108Tir Vlad Ioan Vlad3108 Data 26 octombrie 2024 13:43:35
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.42 kb
#pragma region TEMPLATES

#include <bits/stdc++.h>
using namespace std;
typedef long long i64;
typedef unsigned long long u64;

const string file = "dijkstra";
void init() {
#ifdef DEBUG
    freopen( "in.txt",  "r", stdin);
#elif LOCAL
    freopen( "in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#else
    cin.tie(0)->sync_with_stdio(0);
    if (!file.empty()) {
        freopen((file +  ".in").c_str(), "r", stdin);
        freopen((file + ".out").c_str(), "w", stdout);
    }
#endif
}

#ifndef LOCAL
    #define debug(...) 69420
    #define init_test(...) 69420
#else
void init_test(int t) {
    cerr << "\nTEST #" << t << "\n";
}
template<typename T>
void debug(T n) {
    cerr << n << "\n";
}
template<typename T, typename... Args>
void debug(T n, Args... args) {
    cerr << n << " ";
    debug(args...);
}
template<typename T>
void debug(const vector<T> &v) {
    for (const auto &it : v) {
        cerr << it << " ";
    }
    cerr << "\n";
}
#endif

void solve();
int main() {
    init();
    int t = 1;
    // cin >> t;
    for (int i = 1; i <= t; ++i) {
        init_test(i);
        solve();
    }
}

#pragma endregion TEMPLATES

// Dijkstra's Algorithm
vector<i64> Dijkstra(int node,
        const vector<vector<pair<int, int> > > &G) {
    // G[i] contains edges {j, cost}
    priority_queue<pair<i64, i64>,
        vector<pair<i64, i64> >, greater<> > pq;
    vector<i64> dist(G.size(), LLONG_MAX);
    dist[node] = 0;
    pq.push({node, 0});
    while (!pq.empty()) {
        int node;
        i64 cost;
        tie(node, cost) = pq.top();
        pq.pop();

        if (dist[node] != cost) {
            continue;
        }
        for (const auto &it : G[node]) {
            if (cost + it.second < dist[it.first]){
                dist[it.first] = cost + it.second;
                pq.push({it.first, dist[it.first]});
            }
        }
    }
    return dist;
}

void solve() {
    int n, m;
    cin >> n >> m;
    vector< vector< pair<int, int> > > G(n + 1);
    while (m--) {
        int u_i, v_i, w_i;
        cin >> u_i >> v_i >> w_i;
        G[u_i].push_back({v_i, w_i});
        G[v_i].push_back({u_i, w_i});
    }
    vector<i64> dist = Dijkstra(1, G);
    for (int i = 2; i <= n; ++i) {
        if (dist[i] == LLONG_MAX) {
            cout << " ";
        }
        else {
            cout << dist[i] << " ";
        }
    }
}