Cod sursa(job #3344425)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 1 martie 2026 23:01:52
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 50005;
vector<pair<int,int>> graph[MAX];
vector<int> dist;

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 top = pq.top();
        int node = top.second;
        pq.pop();

        for (auto next : graph[node])
        {
            if (dist[next.first] > dist[node]+next.second)
            {
                dist[next.first] = dist[node]+next.second;
                pq.push({dist[next.first], next.first});
            }
        }
    }
}

int main()
{
    ifstream fin("dijkstra.in");
    ofstream fout("dijkstra.out");
    int n, m;
    fin >> n >> m;
    dist.assign(n+1, INT_MAX);

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

    dijkstra();

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

    return 0;
}