Cod sursa(job #3337196)

Utilizator KoshamrPetru Draghiceanu Koshamr Data 27 ianuarie 2026 00:12:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;

// Use a large enough infinity value (approx 2 billion)
// Max path could be ~50,000 nodes * 20,000 weight = 1,000,000,000
const int INF = 2000000000;

int n, m;
vector<vector<pair<int, int>>> adj;
vector<int> dist;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

void dijkstra(int start)
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

    dist[start] = 0;
    pq.push({0, start});

    while (!pq.empty())
    {
        int d = pq.top().first;
        int u = pq.top().second;
        pq.pop();
        if (d > dist[u])
            continue;

        for (auto edge : adj[u])
        {
            int v = edge.second;
            int cost = edge.first;

            // Relaxation step
            if (dist[u] + cost < dist[v])
            {
                dist[v] = dist[u] + cost;
                pq.push({dist[v], v});
            }
        }
    }
}

int main()
{
    fin >> n >> m;

    adj.assign(n + 1, {});
    dist.assign(n + 1, INF);

    for (int i = 0; i < m; i++)
    {
        int u, v, w;
        fin >> u >> v >> w;
         adj[u].push_back({w, v});
    }

    dijkstra(1);

    for (int i = 2; i <= n; i++)
    {
        
        if (dist[i] == INF)
        {
            fout << "0 ";
        }
        else
        {
            fout << dist[i] << " ";
        }
    }

    return 0;
}