Cod sursa(job #3337044)

Utilizator petru-robuRobu Petru petru-robu Data 26 ianuarie 2026 21:14:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;

int n, m;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

vector<vector<pair<int, int>>> adj_list;
vector<int> dist;

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

    adj_list.assign(n+1, {});
    dist.assign(n+1, INT_MAX);

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

void dijkstra()
{
    priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq;
    pq.push({0, 1});
    dist[1] = 0;

    while(!pq.empty())
    {
        auto [curr_cost, curr_x] = pq.top();
        pq.pop();

        if(dist[curr_x] != curr_cost)
            continue;

        for(auto &next:adj_list[curr_x])
        {
            auto [next_cost, next_x] = next;

            if(dist[next_x] > dist[curr_x] + next_cost)
            {
                dist[next_x] =  dist[curr_x] + next_cost;
                pq.push({dist[next_x], next_x});
            }
        }
    }
}

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

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