Cod sursa(job #3238580)

Utilizator stefanrotaruRotaru Stefan-Florin stefanrotaru Data 26 iulie 2024 19:06:25
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 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];

int viz[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()) {
        pair <long long, int> cur = q.top();

        q.pop();

        if (viz[cur.second]) {
            continue;
        }

        viz[cur.second] = 1;

        for (auto vecin : a[cur.second]) {
            int next = vecin.first;
            int val = vecin.second;

            if (cur.first + val < cost[next]) {
                cost[next] = cur.first + val;
                q.push({cost[next], next});
            }
        }
    }
}

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 << '\n';
        }
    }

    return 0;
}