Cod sursa(job #3202258)

Utilizator theo234Badea Razvan Theodor theo234 Data 11 februarie 2024 11:25:44
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <queue>
#include <limits>

using namespace std;

const int INF = numeric_limits<int>::max();

struct Edge {
    int dest;
    int weight;
};

ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

void dijkstra(vector<vector<Edge>>& graph, vector<int>& dist, int start) {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, start});
    dist[start] = 0;

    while(!pq.empty()){
        int u = pq.top().second;
        int dist_u = pq.top().first;
        pq.pop();

        if(dist_u > dist[u])
            continue;

        for(const Edge& edge : graph[u]){
            int v = edge.dest;
            int w = edge.weight;
            if(dist[u] + w < dist[v]){
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<Edge>> a(n + 1);
    vector<int> dist(n + 1, INF);
    dist[1] = 0;

    for(int i = 0; i < m; i++){
        int x, y, c;
        cin >> x >> y >> c;
        a[x].push_back({y, c});
    }

    dijkstra(a, dist, 1);
    for(int i = 2; i <= n; i++)
        cout << dist[i] << " ";
    cout.close();
    return 0;
}