Cod sursa(job #2695986)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 15 ianuarie 2021 00:32:34
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 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");

    std :: cin >> 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;
    }

    while (!pq.empty()) {
        std::pair<int, int> node = pq.top();
        pq.pop();
        if (dist[node.second] != -node.first) continue;
        for (int i = 0; i < graph[node.second].size(); ++i) {
            int next = graph[node.second][i].first;
            int cost = graph[node.second][i].second;
            if (dist[next] > dist[node.second] + cost) {
                dist[next] = dist[node.second] + cost;
                pq.push({-dist[next], next}); /// pt minim
            }
        }

    }
    for (int i = 2; i <= n; ++i) {
        if (dist[i] != INF) {
            std :: cout << dist[i] << " ";
        } else {
            std :: cout << 0 << " ";
        }
    }
    return 0;
}