Cod sursa(job #3324937)

Utilizator petru-robuRobu Petru petru-robu Data 24 noiembrie 2025 10:35:56
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

struct Node
{
    ll x, c;
    Node(ll x, ll c) : x(x), c(c) {}
};

const ll inf = (1LL<<60);

vector<vector<Node>> adj_list;
vector<ll> dist, parent;
ll n, m;

void read()
{
    fin >> n >> m;

    adj_list.assign(n + 1, {});
    dist.assign(n + 1, inf);
    parent.assign(n + 1, 0);

    dist[1] = 0;

    for (ll i = 0; i < m; i++)
    {
        ll x, y, c;
        fin >> x >> y >> c;
        adj_list[x].push_back(Node(y, c));
    }
}

void dijkstra()
{
    priority_queue< pair<ll, ll> , vector<pair<ll, ll>>, greater<pair<ll,ll>> > Q;

    Q.push({dist[1], 1});
    while (!Q.empty())
    {
        auto [d, curr] = Q.top();
        Q.pop();

        if(d != dist[curr])
            continue;
        
        for (auto &next : adj_list[curr])
        {
            if (dist[curr] + next.c < dist[next.x])
            {
                dist[next.x] = dist[curr] + next.c;
                parent[next.x] = curr;
                Q.push({dist[next.x], next.x});
            }
        }
    }
}

int main()
{
    read();
    dijkstra();

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

    return 0;
}