Cod sursa(job #3227051)

Utilizator andreea678Rusu Andreea andreea678 Data 24 aprilie 2024 19:21:49
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <queue>
#include <fstream>
#include <vector>
#define INF 0x7f7f7f7f
using namespace std;

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

int n, m;
int nsursa, ndestinatie, cost;
vector<vector<pair<int, int>>> gr;///gr[nsursa] = first-nodul destinatie, second-cost pana la nod destinatie
vector<int> dist;

void dijkstra(int nod) {
    dist.assign(n + 1, INF);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; ///first-distanta de la nodul 0 la nodul x; second-nodul x
    dist[nod] = 0;
    pq.push({0, nod});
    while (!pq.empty()) {
        int u = pq.top().second;
        if (dist[u]==pq.top().first){
            for (auto &neighbor : gr[u]) {
                int v = neighbor.first;
                int edge_cost = neighbor.second;
                if (dist[v] > dist[u] + edge_cost) {
                    dist[v] = dist[u] + edge_cost;
                    pq.push({dist[v], v});
                }
            }
        }
        pq.pop();
    }
}

int main() {
    fin >> n >> m;
    gr.resize(n + 1);
    for (int i = 1; i <= m; ++i) {
        fin >> nsursa >> ndestinatie >> cost;
        gr[nsursa].push_back({ndestinatie, cost});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if (dist[i]==INF){
            fout << 0 << ' ';
        }
        else fout << dist[i] << ' ';
    }
    return 0;
}