Cod sursa(job #3344520)

Utilizator Mihaita09Nechitescu Mihai Mihaita09 Data 2 martie 2026 10:59:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

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

#define cin fin
#define cout fout

struct el{
    int nod, cost;
    bool operator < (const el&other) const{
        return cost > other.cost;
    }
};

vector<el> v[50001];
int dist[50001],n,m,x,y,c;
priority_queue<el> pq;
bool viz[50001];

void dijkstra(int start)
{
    for (int i = 1 ; i <= n; i++){
        dist[i] = 1e9;
    }
    dist[start] = 0;
    pq.push({start,0});
    while(!pq.empty())
    {
        el x=pq.top();
        pq.pop();
        if (!viz[x.nod]){
        viz[x.nod] = 1;
            for(auto e:v[x.nod])
            {
                if (viz[e.nod] == 0)
                {
                  dist[e.nod] = min(dist[e.nod], e.cost + dist[x.nod]);
                  pq.push({e.nod,dist[e.nod]});
                }

            }
        }
    }
}

int main(){
    cin >> n >> m;
    for (int i = 1 ; i <= m; i++)
    {
        cin >> x >> y >> c;
        v[x].push_back({y,c});
    }
    dijkstra(1);
    for (int i = 2 ; i <= n; i++)
    {
        if (dist[i] == 1e9) cout << '0' << " ";
        else cout << dist[i] << " ";
    }

}