Cod sursa(job #2695979)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 15 ianuarie 2021 00:08:16
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const int N_MAX = 100005;
const int INF = 1e9;

std::vector<std::pair<int, int> > graph[N_MAX];
std::priority_queue<std::pair<int, int> > pq;
bool vis[N_MAX];
int dist[N_MAX];
int n, m;

int main() {
    std::ifstream fin("dijkstra.in");
    std::ofstream fout("dijkstra.out");

    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, cost;
        std::cin >> x >> y >> cost;
        graph[x].push_back({y, cost});
    }
    dist[1] = 0;
    pq.push({0, 1});
    for (int i = 2; i <= n; i++) {
            dist[i] = INF;
            vis[i] = false;
    }

    while (!pq.empty()) {
        int node = pq.top().second;
        pq.pop();
        if (!vis[node]) {
            vis[node] = true;
            for (int i = 0; i < graph[node].size(); ++i) {
                int next = graph[node][i].first;
                int cost = graph[node][i].second;
                if (dist[next] > dist[node] + cost) {
                    dist[next] = dist[node] + cost;
                    pq.push({-dist[next], next}); /// pt minim
                }
            }
        }
    }
    for (int i = 2; i <= n; ++i) {
        if (dist[i] != INF) {
            fout << dist[i] << " ";
        }
        else {
            fout << 0 << " ";
        }
    }
    return 0;
}