Cod sursa(job #3225157)

Utilizator Mihai_OctMihai Octavian Mihai_Oct Data 16 aprilie 2024 22:34:09
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int inf = 1e7 + 2;
struct Muchie {
    int x, y, c;
};
vector<Muchie> a[50002];
int n, m, p, q, i, x, y, c;
int d[50002];

static inline void Dijkastra(int nod = 1) {
    ///     cost, nod
    set<pair<int, int>> q;
    q.insert({0, nod});

    d[nod] = 0;

    while(!q.empty()) {
        int nod = q.begin()->second;
        q.erase(q.begin());

        for(auto vec : a[nod]) {
            if(d[vec.y] > d[vec.x] + vec.c) {
                q.erase({d[vec.y], vec.y});

                d[vec.y] = d[vec.x] + vec.c;

                q.insert({d[vec.y], vec.y});
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for(i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        a[x].push_back({x, y, c});
        a[y].push_back({y, x, c});
    }

    for(i = 1; i <= n; i++) d[i] = inf;
    Dijkastra();

    for(i = 2; i <= n; i++) fout << d[i] << " ";

    return 0;
}