Cod sursa(job #2587131)

Utilizator k2e0e0w3qDumitrescu Gheorghe k2e0e0w3q Data 22 martie 2020 01:05:41
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

#define NMAX 50001

#define INF 0x3F3F3F3F

using namespace std;



class cmp {

public:

    bool operator () (const pair <int, int> &a, const pair <int, int> &b) {

        return a.second>b.second;

    }

};



vector <pair <int, int>> G[NMAX];

priority_queue <pair <int, int>, vector <pair <int, int>>, cmp> PQ;

array <int, NMAX> dist;

array <bool, NMAX> beenThere;

int main (void) {

    ifstream fin ("dijkstra.in");

    ofstream fout ("dijkstra.out");

    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);

    beenThere.fill(false);

    dist[1]=0;

    PQ.push(make_pair(1, 0));



    while (!PQ.empty()) {

        while (!PQ.empty() && beenThere[PQ.top().first])

            PQ.pop();



        if (!PQ.empty()) {

            auto save=PQ.top();

            PQ.pop();

            beenThere[save.first]=1;

            if (dist[save.first]==save.second)

                for (auto it: G[save.first])

                    if (dist[it.first]>save.second+it.second) {

                        dist[it.first]=save.second+it.second;

                        PQ.push(make_pair(it.first, dist[it.first]));

                    }

        }

    }



    for (i=2; i<=n; i++) {

        if (dist[i]==INF)

            dist[i]=0;

        fout << dist[i] << ' ';

    }

    return 0;

}