Cod sursa(job #3237280)

Utilizator Cyb3rBoltSbora Ioan-David Cyb3rBolt Data 8 iulie 2024 08:30:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int DIM = 50010;
int n, m, distanta[DIM];

struct Iris {
    int vecin, val;
};
vector<Iris> muchii[DIM];

struct cmp {
    bool operator()(Iris a, Iris b) {
        return a.val > b.val;
    }
};

priority_queue<Iris, vector<Iris>, cmp> q;

inline void dijkstra(int start, int costDrum) {
    for(int i=1; i<=n; i++) distanta[i] = 2e9;
    distanta[start] = 0, q.push({start, 0});
    while(!q.empty()) {
        int nod = q.top().vecin;
        int cost = q.top().val;
        q.pop();
        if(distanta[nod] >= cost) {
            for(Iris i : muchii[nod]) {
                int vecin = i.vecin, val = i.val;
                if(distanta[nod] + val < distanta[vecin]) {
                    distanta[vecin] = distanta[nod] + val;
                    q.push({vecin, distanta[vecin]});
                }
            }
        }
    }
}

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

    return 0;
}