Cod sursa(job #2775749)

Utilizator alextmAlexandru Toma alextm Data 16 septembrie 2021 22:39:54
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>
using namespace std;

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

const int INF = 0x3F3F3F3F;
const int MAXN = 100001;
typedef pair<int,int> PII;

priority_queue<PII, vector<PII>, greater<PII>> heap;
vector<PII> G[MAXN];
int d[MAXN], viz[MAXN];

int main() {
    int n, m, p, x, y, c;

    fin >> n >> m;
    while(m--) {
        fin >> x >> y >> c;
        G[x].emplace_back(y, c);
    }

    for(int i = 1; i <= n; i++)
        d[i] = INF;

    d[1] = 0;
    heap.push({0, 1});

    while(!heap.empty()) {
        int node = heap.top().second;
        heap.pop();

        if(viz[node] == 0) {
            viz[node] = 1;
            for(auto nxt : G[node]) {
                if(d[node] + nxt.second < d[nxt.first]) {
                    d[nxt.first] = d[node] + nxt.second;
                    heap.push({d[nxt.first], nxt.first});
                }
            }
        }
    }

    for(int i = 2; i <= n; i++)
        fout << (d[i] == INF ? -1 : d[i]) << " ";
    fout << '\n';

    return 0;
}