Cod sursa(job #3319519)

Utilizator EckchartZgarcea Robert-Andrei Eckchart Data 1 noiembrie 2025 19:29:38
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pi = pair<int, int>;
using pll = pair<ll, ll>;
using pd = pair<double, double>;
using pld = pair<ld, ld>;
// #define LOCAL
#ifdef LOCAL
ifstream cin("input.txt");
ofstream cout("output2.txt");
#else
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
#endif
#define cin ::cin
#define cout ::cout


int main()
{
    int N, M;
    cin >> N >> M;
    vector<vector<pi>> adj;
    adj.resize(N + 1);
    while (M--)
    {
        int A, B, C;
        cin >> A >> B >> C;
        adj[A].push_back({B, C});
    }

    const int source_vertex = 1;
    const int INF = 2e9;

    [&]() -> void
    {
        vector<int> shortest_paths(N + 1, INF);
        vector<bool> was_marked(N + 1, false);
        shortest_paths[source_vertex] = 0;
        for (int i = 0; i < N; ++i)
        {
            int min_node = -1;
            for (int j = 1; j <= N; ++j)
            {
                if (was_marked[j] || (min_node != -1 && shortest_paths[j] > shortest_paths[min_node]))
                {
                    continue;
                }
                min_node = j;
            }
            if (shortest_paths[min_node] == INF)
            {
                break;
            }
            was_marked[min_node] = true;

            for (const auto &anode : adj[min_node])
            {
                const int adj_node = anode.first;
                const int weight = anode.second;
                if (shortest_paths[min_node] + weight < shortest_paths[adj_node])
                {
                    shortest_paths[adj_node] = shortest_paths[min_node] + weight;  // RELAX BRO
                }
            }
        }

        for (int i = 2; i <= N; ++i)
        {
            cout << (shortest_paths[i] == INF ? 0 : shortest_paths[i]) << " ";
        }
    }();
}