Cod sursa(job #3197714)

Utilizator Manolea_Teodor_StefanManolea Teodor Stefan Manolea_Teodor_Stefan Data 27 ianuarie 2024 12:26:08
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
#define INF INT_MAX
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

int N,M;
vector<bool> usedNodes;
vector<int> costNode;
vector<unordered_map<int,int>> G;

int main() {
    fin >> N >> M;
    usedNodes.assign(N+1, false);
    costNode.assign(N+1,INF);
    G.resize(N+1);
    for (int i = 1; i <= M; i++) {
        int nodeA,nodeB,cost;
        fin >> nodeA >> nodeB >> cost;
        G[nodeA][nodeB] = cost;
        G[nodeB][nodeA] = cost;
    }
    queue<int> nodes;
    nodes.push(1);
    costNode[1] = 0;
    while (!nodes.empty()) {
        usedNodes[nodes.front()] = true;
        for (const pair<int,int>& edge : G[nodes.front()]) {
            if (costNode[nodes.front()] + edge.second <= costNode[edge.first]) {
                costNode[edge.first] = costNode[nodes.front()] + edge.second;
                if (!usedNodes[edge.first]) {
                    nodes.push(edge.first);
                }
            }
        }
        nodes.pop();
    }
    for (int i = 2; i <= N; i++) {
        fout << costNode[i] << ' ';
    }
    return 0;
}