Cod sursa(job #3284481)

Utilizator PsyDuck1914Feraru Rares-Serban PsyDuck1914 Data 11 martie 2025 17:46:56
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f ("dijkstra.in");
ofstream g ("dijkstra.out");

const int NMAX = 5e4;
vector<pair<int, int>> adj[NMAX + 1];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

int n, m;

int dist[NMAX + 1];



void dijkstra(int nod){
    
    dist[nod] = 0;
    pq.push({0, nod});
    
    while(!pq.empty()){
        
        int fromnod = pq.top().second;
        int fromcost = pq.top().first;
        
        pq.pop();
        
        if(fromcost > dist[fromnod])
            continue;
            
        for(auto next : adj[fromnod]){
            
            int tocost = next.second;
            int tonod = next.first;
            
            if(dist[tonod] > dist[fromnod] + tocost){
                
                dist[tonod] = dist[fromnod] + tocost;
                
                pq.push({dist[tonod], tonod});
                
            }
            
        }
        
    }
    
}

int main()
{
    
    f >> n >> m;
    
    for(int i=1; i<=m; i++){
        
        int x, y, cost;
        f >> x >> y >> cost;
        
        adj[x].push_back({y, cost});
        adj[y].push_back({x, cost});
        
    }
    
    for(int i=1; i<=n; i++)
        dist[i] = 2e9;
    
    dijkstra(1);
    
    for(int i=2; i<=n; i++)
        if(dist[i] == 2e9)
            g << 0 << ' ';
        else
            g << dist[i] << ' ';

    return 0;
}