Cod sursa(job #3238602)

Utilizator stefanrotaruRotaru Stefan-Florin stefanrotaru Data 28 iulie 2024 09:40:34
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n, m;

vector < vector <pair <int, int> > > a;

vector <long long> cost;

vector <bool> viz;

priority_queue < pair <long long, int>, vector <pair<long long, int> >, greater <pair <long long, int> > > q;

void dijkstra()
{
    cost[1] = 0;

    q.push({0, 1});

    while (!q.empty()) {
        int nod = q.top().second;
        long long val = q.top().first;

        q.pop();

        if (viz[nod]) {
            continue;
        }

        viz[nod] = 1;

        for (auto vecin : a[nod]) {
            if (val + vecin.second < cost[vecin.first]) {
                cost[vecin.first] = val + vecin.second;
                q.push({cost[vecin.first], vecin.first});
            }
        }
    }

    for (int i = 2; i <= n; ++i) {
        if (cost[i] == (1LL << 60)) {
            cost[i] = 0;
        }
    }
}

int main()
{
    f >> n >> m;

    a.resize(n + 5), viz.resize(n + 5), cost.resize(n + 5, (1LL << 60));

    for (int i = 1; i <= m; ++i) {
        int x, y, z;

        f >> x >> y >> z;

        a[x].push_back({y, z});
        a[y].push_back({x, z});
    }

    dijkstra();

    for (int i = 2; i <= n; ++i) {
        g << cost[i] << ' ';
    }

    return 0;
}