Cod sursa(job #3205019)

Utilizator danutbodbodnariuc danut danutbod Data 18 februarie 2024 17:19:33
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
#define M 50003
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int d[M],sel[M];
int n, m, i, x, y, c,inf = 1e9;

priority_queue<pair<int, int>> q;      //q - min heap <cost_minim,nod>
vector<pair<int, int>> a[M];         //a[x] are muchii  (x,y) <y,cost>

void dijkstra(int nod) {
    int c, x;
    q.push({0, nod});
    sel[nod]=1;
    while(!q.empty()) {
        c = -q.top().first;       //c -cost_minim
        x = q.top().second;      //x -nod
        q.pop();
        for(auto y : a[x])
            if(!sel[y.first])
            {
                if(d[y.first]>c+y.second) d[y.first]=c+y.second;
                sel[y.first]=1;
                q.push({-d[y.first],y.first});
            }
    }
}

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

    return 0;
}