Cod sursa(job #2775739)

Utilizator alextmAlexandru Toma alextm Data 16 septembrie 2021 22:21:10
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 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 >> p;
    while(m--) {
        fin >> x >> y >> c;
        G[x].emplace_back(y, c);
        G[y].emplace_back(x, c);
    }

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

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

    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;
}