Cod sursa(job #3344517)

Utilizator Mihaita09Nechitescu Mihai Mihaita09 Data 2 martie 2026 10:55:09
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 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[10001];
int dist[10001],n,m,x,y,c;
priority_queue<el> pq;
bool viz[10001];

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});
        v[y].push_back({x,c});
    }
    dijkstra(1);
    for (int i = 2 ; i <= n; i++)
    {
        cout << dist[i] << " ";
    }

}