Cod sursa(job #3375692)

Utilizator dragosdragonnIosub Dragos Casian dragosdragonn Data 13 noiembrie 2026 08:30:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
vector<vector<pair<int, int>>> L;
vector<int> d; 
vector<int> viz;

void dijkstra(int sursa)
{
    d.assign(n + 1, 1e9);
    viz.assign(n + 1, 0);
    d[sursa] = 0;
    
    priority_queue<pair<int, int>> pq;
    pq.push({-d[sursa], sursa});
    
    while(!pq.empty())
    {
        int nod = pq.top().second;
        pq.pop();
        
        if(viz[nod])
            continue;
        viz[nod] = 1;
        
        for(auto it : L[nod])
        {
            int vec = it.first;
            int cost = it.second;
            
            if(d[vec] > d[nod] + cost)
            {
                d[vec] = d[nod] + cost;
                pq.push({-d[vec], vec});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    
    L.resize(n + 1);
    
    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        L[x].push_back({y, c});
    }
    
    dijkstra(1);
    
    for(int i = 2; i <= n; i++)
    {
        if(d[i] == 1e9)
            fout << 0 << " ";
        else
            fout << d[i] << " ";
    }
    return 0;
}