Cod sursa(job #3337147)

Utilizator SomethingAndrei Marian Something Data 26 ianuarie 2026 22:50:05
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

const int INF = 1e9;
vector<vector<pair<int, int>>> lista;

void prim(int n, int nod_start)
{
    // {distanta_de_la_nod_start, nod_curent}
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    vector<int> dist(n, INF);
    dist[nod_start - 1] = 0;
    pq.push({0, nod_start});
    while(!pq.empty())
    {
        int distanta = pq.top().first; // distanta pana aici
        int nod_curent = pq.top().second;
        pq.pop();

        if(distanta > dist[nod_curent - 1])
            continue;

        for(auto vecin : lista[nod_curent - 1])
        {
            // vector<pair<int, int>>
            int v = vecin.first;
            int c = vecin.second;
            if(dist[v - 1] > dist[nod_curent - 1] + c)
            {
                dist[v - 1] = dist[nod_curent - 1] + c;
                pq.push({dist[v - 1], v});
            }
        }
    }
    for(int i = 1; i < n; i++)
    if(dist[i] == INF)
        g << 0 << " ";
    else
        g << dist[i] << " ";
}

int main()
{
    int n, m, x, y, cost;
    f >> n >> m;
    lista.resize(n);
    for(int i = 0; i < m; i++)
    {
        f >> x >> y >> cost;
        lista[x - 1].push_back({y, cost});
        lista[y - 1].push_back({x, cost});
    }

    prim(n, 1);
    return 0;
}