Cod sursa(job #3285691)

Utilizator AlexTrTrambitas Alexandru-Luca AlexTr Data 13 martie 2025 13:05:32
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <set>
#include <vector>

using namespace std;

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

const int INF = 2e9, NMAX = 50000;

set<pair<int, int>> S;
vector<pair<int, int>> lista[NMAX + 1];

int n, m, x, y, cost, D[NMAX + 1];

void Dijkstra(int node)
{
    D[node] = 0;
    S.insert(make_pair(0, node));

    while (!S.empty())
    {
        pair<int, int> current = *(S.begin());
        S.erase(S.begin());

        int currentNode = current.second;

        for (int i = 0; i<lista[currentNode].size(); ++i)
        {
            int nextNode = lista[currentNode][i].first;
            int nextCost = lista[currentNode][i].second;
            if (D[nextNode] > D[currentNode] + nextCost)
            {
                if (D[nextNode] != INF)
                    S.erase(S.find(make_pair(D[nextNode], nextNode)));

                D[nextNode] = D[currentNode] + nextCost;

                S.insert(make_pair(D[nextNode], nextNode));
            }

        }


    }
}

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

    Dijkstra(1);

    for (int i = 2; i<=n; ++i)
        g << D[i] << ' ';
    return 0;
}