Cod sursa(job #2587112)

Utilizator s.gabi7Dumitrescu Daniel s.gabi7 Data 22 martie 2020 00:48:45
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#define N 50001
#define INF 0x3F3F3F3F
using namespace std;

array <int, N> dist;
vector <pair <int, int>> G[N];
bitset <N> seen;
int main () {
    ifstream fin ("dijkstra.in");
    ofstream fout ("dijkstra.out");
    ios::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    int n, m, i, j, c;
    fin >> n >> m;
    for (; m; m--) {
        fin >> i >> j >> c;
        G[i].push_back(make_pair(j, c));
    }

    dist.fill(INF);
    dist[1]=0;
    auto cmp = [&] (const pair <int, int> &a, const pair <int, int> &b) -> bool {
        return a.second < b.second;
    };
    priority_queue <pair <int, int>, vector <pair <int, int>>, decltype(cmp)> PQ(cmp);
    PQ.push(make_pair(1, 0));

    while (!PQ.empty()) {
        while (!PQ.empty() && seen[PQ.top().first])
            PQ.pop();

        if (!PQ.empty()) {
            auto save=PQ.top();
            PQ.pop();

            seen[save.first]=1;
            if (dist[save.first]==save.second)
                for (auto it: G[save.first])
                    if (dist[it.first]>it.second+save.second)
                        dist[it.first]=it.second+save.second,
                        PQ.push(make_pair(it.first, dist[it.first]));
        }
    }

    for (i=2; i<=n; i++)
        if (dist[i]==INF)
            fout << "0 ";
        else
            fout << dist[i] << ' ';
    return 0;
}