Cod sursa(job #3237542)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 9 iulie 2024 21:24:05
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAX_NUM = 15100;

int n, m;
vector<pair<int, int>> graph[MAX_NUM];
vector<int> d(MAX_NUM, INT_MAX);
vector<bool> visited(MAX_NUM, false);

int main() {
    fin >> n >> m;
    for (int  i = 0; i < m; ++i) {
        int a, b, c;
        fin >> a >> b >> c;
        graph[a].push_back({b, c});
    }
    int s = 1;
    d[s] = 0;
    for (int i = 1; i <= n; ++i) {
        int minDist = INT_MAX;
        int currentNode = -1;
        for (int j = 1; j <= n; ++j) {
            if (!visited[j] && d[j] < minDist) {
                minDist = d[j];
                currentNode = j;
            }
        }
        if (currentNode == -1) {
            break;
        }
        visited[currentNode] = true;
        for (auto edge : graph[currentNode]) {
            int node = edge.first, cost = edge.second;
            if (d[currentNode] + cost < d[node]) {
                d[node] = d[currentNode] + cost;
            }
        }
    }
    for (int i = 2; i <= n; ++i) {
        if (d[i] == INT_MAX) {
            fout << "0 ";
        } else {
            fout << d[i] << " ";
        }
    }
    return 0;
}