Cod sursa(job #3238584)

Utilizator stefanrotaruRotaru Stefan-Florin stefanrotaru Data 26 iulie 2024 19:22:25
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int n, m;

long long cost[50005];

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

vector < vector <pair <int, int> > > a(50005);

void dijkstra()
{
    for (int i = 1; i <= n; ++i) {
        cost[i] = (1LL << 60);
    }

    cost[1] = 0;

    q.push({0, 1});

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

        q.pop();

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

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

    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) {
        if (cost[i] != (1LL << 60)) {
            g << cost[i] << ' ';
        }
        else {
            g << 0 << ' ';
        }
    }

    return 0;
}