Cod sursa(job #3328023)

Utilizator GoreaRaresGorea Rares-Andrei GoreaRares Data 5 decembrie 2025 22:12:18
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
#define inf INT_MAX

using namespace std;

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

int n, m, dist[50001];
vector<pair<int, int>> adj[50001];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

void read(){
    int x, y, c;
    fin >> n >> m;
    for(int i = 1; i <= m; i++){
        fin >> x >> y >> c;
        adj[x].push_back({y, c});
        dist[x] = dist[y] = inf;
    }
}

void dijkstra(){
    dist[1] = 0;
    pq.push({0, 1});
    while(!pq.empty()){
        auto [d, u] = pq.top();
        pq.pop();
        if(d != dist[u]) continue;
        for(auto i : adj[u]){
            int v = i.first, cost = i.second;
            if(cost + dist[u] < dist[v])
                dist[v] = cost + dist[u], pq.push({dist[v], v});
        }
    }
    for(int i = 2; i <= n; i++)
        fout << (dist[i] != inf ? dist[i] : 0) << " ";
}

int main()
{
	read();
    dijkstra();
    return 0;
}