Cod sursa(job #3167442)

Utilizator R4phaCrisan Andrei R4pha Data 10 noiembrie 2023 18:41:57
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int MAX_N = 50000;
const int MAX_M = 250000;

vector<pair<int, int>>graph[MAX_N+1];

int n,m;

void dijkstra(int cautat) {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    vector<int> dist(n + 1, INT_MAX);

    dist[cautat] = 0;
    pq.push({0, 1});

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

        if (cost > dist[u]) continue;

        for ( pair<int,int> arc : graph[u]) {
            int v = arc.first;
            int weight = arc.second;

            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }

    for (int i = 2; i <= n; i++) {
        fout << dist[i] << " ";
    }
    fout.close();
}

void Citire(){
    fin>>n>>m;
    for(int i=1;i<=m;i++){
        int a,b,c;
        fin>>a>>b>>c;
        graph[a].push_back({b,c});
    }
}

int main()
{
    Citire();
    dijkstra(1);
    return 0;
}