Cod sursa(job #2781327)

Utilizator Iulia25Hosu Iulia Iulia25 Data 9 octombrie 2021 10:01:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");

const int N = 5e4 + 5;

struct muchie   {
    int nod, cost;
};

auto cmp = [](pair <int, int> x, pair <int, int> y) {
    return x.first > y.first;
};

int n, m;
int viz[N], cost[N];

vector <muchie> v[N];
priority_queue <pair <int, int>, vector <pair <int, int> >, decltype(cmp)> pq(cmp);

void dijkstra() {
    for (int i = 2; i <= n; ++i)
        cost[i] = 2e9;
    pq.push({0, 1});

    while (!pq.empty()) {
        pair <int, int> nod_curent = pq.top();
        pq.pop();
        if (viz[nod_curent.second])
            continue;
        viz[nod_curent.second] = 1;

        for (auto it : v[nod_curent.second])    {
            if (cost[it.nod] > nod_curent.first + it.cost)  {
                cost[it.nod] = nod_curent.first + it.cost;
                pq.push({cost[it.nod], it.nod});
            }
        }

    }
}

int main()  {
    cin >> n >> m;
    int a, b, c;
    for (int i = 1; i <= m; ++i)    {
        cin >> a >> b >> c;
        v[a].push_back({b, c});
    }
    dijkstra();
    for (int i = 2; i <= n; ++i)    {
        if (cost[i] == 2e9)
            cout << 0 << ' ';
        else
            cout << cost[i] << ' ';
    }
    return 0;
}